How Can I Combine Slicing and Reversing to Determine Palindromes in Python?

  • Python
  • Thread starter WWGD
  • Start date
  • Tags
    String
In summary, the code is written to reverse a string, but it is not running. The author is trying to combine two functions to determine whether a string is a palindrome, but the code does not work.
  • #1
WWGD
Science Advisor
Gold Member
7,038
10,642
TL;DR Summary
I have code , a function Rev(x) I wrote, to determine the reverse of a string . I want to use it to determine whether a string is a palindrome, test whether String =Rev(String) . I also want to write another Palindrome tester to practice slicing, which would loop to test whether for a string of length k, String[i]= String{k-i]; i=1,2,..,k

Using Jupyter on Win 10
Hi,
I'm trying to write a program in Python 3 to determine whether a string is a palindrome.
I wrote one already ; it runs, to reverse a string.
I now want to use it to determine palindromes , by testing whether a string equals its reverse.

To practice slicing as well, I want to write the palindrome tester to loop to determine, for a string of length k, whether the
ith spot; i=1,2,..,k equals the (k-i)th spot .

Here's what I have :
1) To reverse

Python:
# Reversing a string :
def Rev(x):
  String = str(x)
  if String[0]= '- ' :
     return int( '-' + String[ :0:-1} )
  else:
     return int( String[:: -1] )

It works. I'm trying to use it to test for Palindromic strings , using the test whether String=Rev(String):
The code below would be written below the above code

Python:
def pal(x):
   String =st(x)
   if String =Rev(String):
      return('Yes, it's a Pal')
   else :
      return('not a Pal')

But it's not running . How can I combine the two definitions above it to determine Palindromes?
Message:
1669942156621.png


Another option is using just the slicing approach as a stand-alone:

Python:
def Pal(x):
  String=Str(x)
  j=len(String)
  For i in range(1,j):
    if String[i] = String[j-i]:
      return('Yes , Pal')
    else:
      return('no, pal')

Error message is :

"File "<ipython-input-30-6b6272cc2aad>", line 10
else:
^
SyntaxError: invalid character in identifier " Any suggestions?
 
Last edited:
Technology news on Phys.org
  • #2
@WWGD, I did my best to edit your code tags to fix them and remove the spurious italic formatting, but it's still not possible to match up any of your error messages with code lines since none of your code blocks have a line 10.

A few suggestions: first, for code tags I find CODE should always be in upper case, and Python code blocks need to have "CODE=Python" specifically (with Python capitalized and no spaces anywhere) for the parser to correctly parse them.

Second, if you are cutting and pasting Python code, do it as plain text (this might not be the default in some code editors) and make sure all of your indentation is spaces, not tabs.

Third, never just say "it works" or "it doesn't work" or "I get this error message". Post the entire raw transcript of what happens when you run the program in a shell.
 
  • Like
Likes jim mcnamara and WWGD
  • #3
PeterDonis said:
@WWGD, I did my best to edit your code tags to fix them and remove the spurious italic formatting, but it's still not possible to match up any of your error messages with code lines since none of your code blocks have a line 10.

A few suggestions: first, for code tags I find CODE should always be in upper case, and Python code blocks need to have "CODE=Python" specifically (with Python capitalized and no spaces anywhere) for the parser to correctly parse them.

Second, if you are cutting and pasting Python code, do it as plain text (this might not be the default in some code editors) and make sure all of your indentation is spaces, not tabs.

Third, never just say "it works" or "it doesn't work" or "I get this error message". Post the entire raw transcript of what happens when you run the program in a shell.
Thanks, just did.
 
  • #4
WWGD said:
Thanks, just did.
The image you posted doesn't look like the same code.
 
  • #5
PeterDonis said:
A few suggestions: first, for code tags I find CODE should always be in upper case, and Python code blocks need to have "CODE=Python" specifically (with Python capitalized and no spaces anywhere) for the parser to correctly parse them.
Capitalizing "code" isn't necessary, nor is capitalizing "python." What is important is that there should not be any spaces in the leading code tag.

Python:
# Reversing a string :
def Rev(x):
  String = str(x)
  if String[0]= '- ' :
     return int( '-' + String[ :0:-1} )
  else:
     return int( String[:: -1] )

What I entered:
[code=python]
# Reversing a string :
def Rev(x):
String = str(x)
if String[0]= '- ' :
return int( '-' + String[ :0:-1} )
else:
return int( String[:: -1] )
[/code]
Note that the above is actually indented, but my fiddling with the code tags causes the text to be displayed without indentation.
 
Last edited:
  • Like
Likes WWGD
  • #6
PeterDonis said:
it's still not possible to match up any of your error messages with code lines since none of your code blocks have a line 10.
Also, you have syntax errors in all of your "if" statements: the equality testing operator in Python is "==", not "=".

Also, I don't understand why you would be returning ints instead of strings in the Rev function.
 
  • Like
Likes scottdave
  • #7
A general question about Jupyter for Python : Do definitions apply throughout in different cells in the same notebook, i.e., if I define a function in cell j of notebook k, can I apply it in any other cell of the same notebook k? Strangely, I've been able to do it only some times. I m ean, I used Rev(x), the function that reverses a string, in the definition of the Pal function, as in : "if String==Rev(String) return("Yes, Pal"), but this hasn't worked other times.

Heading out till tomorrow on PC. Thanks all.
 
Last edited:
  • #8
WWGD said:
A general question about Jupyter for Python : Do definitions apply throughout in different cells in the same notebook, i.e., if I define a function in cell j of notebook k, can I apply it in any other cell of the same notebook k?
I can't say because I don't use Jupyter, or any other such framework. But one of the main reasons I don't is precisely because of such questions: how do you know what environment your code is running in? If you just directly edit .py files you never have any doubt: what's in your .py file explicitly determines what code is accessible (whatever code is defined in the .py file or imported by it). So you always have explicit control over this very important thing.
 
  • #9
PeterDonis said:
Also, you have syntax errors in all of your "if" statements: the equality testing operator in Python is "==", not "=".

Also, I don't understand why you would be returning ints instead of strings in the Rev function.
I think the issue is to write a function that covers numerical strings which may contain a - at the beginning.
Otherwise, for generic strings, we just use slicing , as in : Rev(String) =String[:: -1]. This doesn't work with a - in the begining of the string. But not 100%

And thanks, yes, remembering that = is assignment, while == is for equality testing.
 
  • #10
WWGD said:
I think the issue is to write a function that covers numerical strings which may contain a - at the beginning.
This depends on your definition of "palindrome" and what kind of data you are working with. Are you working with numbers? With only numeric strings? With alphanumeric strings? Do you not count the "-" sign at the start of a numeric string as part of the string?

None of these questions are questions about Python coding. They are questions about the problem specification. If you're not clear about that no amount of coding help will fix it.
 
  • #11
PeterDonis said:
If you just directly edit .py files you never have any doubt: what's in your .py file explicitly determines what code is accessible (whatever code is defined in the .py file or imported by it). So you always have explicit control over this very important thing.
Exactly. I couldn't relate to the whole Jupyter business with functions in cell j in notebook k.
WWGD said:
I think the issue is to write a function that covers numerical strings which may contain a - at the beginning.
But you aren't dealing with these strings as integers -- you're dealing with them as strings of numerical digits. Your functions should return strings, not integers.
 
  • #12
PeterDonis said:
This depends on your definition of "palindrome" and what kind of data you are working with. Are you working with numbers? With only numeric strings? With alphanumeric strings? Do you not count the "-" sign at the start of a numeric string as part of the string?

None of these questions are questions about Python coding. They are questions about the problem specification. If you're not clear about that no amount of coding help will fix it.
Well, for purely numerical strings, reversing, e.g., -23 into 32- won't output a number, so you consider separate cases. If it's alphanumeric, then reversing including the - will output an alpha string. So, yes, I need to know if the string is numerical or not.
A palindromic string is one that is symmetrical about the middle digit. So I wrote it so that the ith element of a string of length k equals the (k-i)th element. ith element being the ith .

This is intended as a basic exercise.
 
  • #13
WWGD said:
for purely numerical strings, reversing, e.g., -23 into 32- won't output a number
Who cares? The definition of a palindromic string has nothing whatever to do with whether the string is valid when interpreted as a number.

WWGD said:
A palindromic string is one that is symmetrical about the middle digit.
No, it isn't. "ABBA" is a palindromic string and doesn't even have any digits in it.

Why are you restricting yourself to numbers?
 
  • #14
PeterDonis said:
Who cares? The definition of a palindromic string has nothing whatever to do with whether the string is valid when interpreted as a number.No, it isn't. "ABBA" is a palindromic string and doesn't even have any digits in it.

Why are you restricting yourself to numbers?
Fair enough. String is symmetrical. I don't remember the specs of this exercise from a while back. It may have been about reversing numbers.
 
  • #15
WWGD said:
Fair enough. String is symmetrical. I don't remember the specs of this exercise from a while back. It may have been about reversing numbers.
From the way you have (tried to) implement it, this is clearly the case.

WWGD said:
Do definitions apply throughout in different cells in the same notebook, i.e., if I define a function in cell j of notebook k, can I apply it in any other cell of the same notebook k?
Yes you can, but...
WWGD said:
Strangely, I've been able to do it only some times.
That's because the code in a cell is not run automatically, you have to tell Jupyter to run it. And if you edit the code, you have to tell Jupyter to run it again.

What Jupyter does behind the scenes is not obvious, and it uses the accursed REPL mode of Python (personal opinion). Because of this I do not recommend learning Python using Jupyter notebooks, it's like learning to drive using Mario Kart.
 
Last edited:
  • Like
Likes WWGD
  • #16
pbuk said:
the accursed REPL mode of Python (personal opinion)
Why do you think Python's REPL is accursed?
 
  • #17
PeterDonis said:
Why do you think Python's REPL is accursed?
Because it confuses the distinction between a programming language and an interactive application, leading to exactly the kind of misunderstanding that we see in this thread.
 
  • #18
pbuk said:
Because it confuses the distinction between a programming language and an interactive application, leading to exactly the kind of misunderstanding that we see in this thread.
It is an interactive application--for programmers. I find it enormously useful for all kinds of things when programming. One just has to be aware of the intended users, as one does for any interactive application. Nobody complains about IDEs being programmer centric, and those, with GUIs, are far more like typical interactive applications than the REPL is.
 
  • #19
Any input on my code?
 
  • #20
WWGD said:
Any input on my code?
I think you need to first decide exactly what requirements the code has to meet. We still don't have a definite answer from you on that.
 
  • #21
Ok. For the first, I want to define a function Rev (X) to reverse an Integer-valued string. Ive used slicing here.

For the second, I want to define a function that makes use the first, to test whether such string is a palindrome, meaning whether it reads the same left-right, as it does right-left. My idea is to test whether String=Rev(String).

For the 3rd, I want to recursively test for a palindrome using slicing, i.e., test whether the term in the 1st place is the same as in the last , then whether the 2nd term is equal to the next-to-last term, etc. Given a string of length k, Im framing, In terms of slices, on whether String[0]=String[k], String[1]=String[k-1], etc.

Hope I was clear. Please let me know otherwise.
 
  • #22
WWGD said:
For the first, I want to define a function Rev (X) to reverse an Integer-valued string
Are you requiring yourself to do it by hand? Or are you allowed to use Python's built-in reversed function?

Note also that your definition of "reverse" does not include the "-" sign for negative integers. Which makes sense, but should be made explicit in your specification of what it means to "reverse an integer-valued string".

WWGD said:
For the second, I want to define a function that makes use the first, to test whether such string is a palindrome, meaning whether it reads the same left-right, as it does right-left. My idea is to test whether String=Rev(String).
Yes, that part is obvious, as long as the Rev function does its job. (Note that, as above, your definition excludes the "-" sign in front of negative integers from consideration.)

WWGD said:
For the 3rd, I want to recursively test for a palindrome using slicing, i.e., test whether the term in the 1st place is the same as in the last , then whether the 2nd term is equal to the next-to-last term, etc.
That's not what your code is doing, since it returns "yes" after only the first test has passed.
 
  • Like
Likes WWGD
  • #23
PeterDonis said:
Are you requiring yourself to do it by hand? Or are you allowed to use Python's built-in reversed function?

Note also that your definition of "reverse" does not include the "-" sign for negative integers. Which makes sense, but should be made explicit in your specification of what it means to "reverse an integer-valued string".Yes, that part is obvious, as long as the Rev function does its job. (Note that, as above, your definition excludes the "-" sign in front of negative integers from consideration.)That's not what your code is doing, since it returns "yes" after only the first test has passed.
Ok, thanks. But if I right a function definition in cell j, can I refer to the same definition in any other cell?
Let me rethink the code for #3.
Thanks for the input.
 
  • #24
WWGD said:
Ok. For the first, I want to define a function Rev (X) to reverse an Integer-valued string.
Why limit the code to strings of integer digits? It appears that you need the Rev() function only to determine whether a string happens to be the same is the one with the characters reversed. You could have a single function that determines whether a string of characters happens to be a palindrome, and that function could be recursive. Is there some reason other than what I've described that you need a Rev() function?
WWGD said:
For the second, I want to define a function that makes use the first, to test whether such string is a palindrome, meaning whether it reads the same left-right, as it does right-left. My idea is to test whether String=Rev(String).
See above. Also note that = is used for assignment, not comparison.

WWGD said:
But if I right a function definition in cell j, can I refer to the same definition in any other cell?
A partial answer was given in post #8 and a more definitive one was given in post #15.
 
  • Like
Likes WWGD
  • #25
Mark44 said:
You could have a single function that determines whether a string of characters happens to be a palindrome
For the OP's benefit, the theoretical advantage of this is that the algorithm will only be O(n), whereas the algorithm "reverse the string and then compare the reversed string with the original" is O(n^2) (since both the reversing and the comparing operations are O(n)). Whether that makes a difference in practice depends on the maximum string length that you expect to be testing.

Mark44 said:
that function could be recursive.
In Python, it's usually better to use for loops where possible since recursive functions can overflow the interpreter's stack.
 
  • #26
PeterDonis said:
In Python, it's usually better to use for loops where possible since recursive functions can overflow the interpreter's stack.
Yes, I recognize this, but @WWGD wanted to cobble together something that was recursive. In any case, I doubt that he will be working with any strings that are long enough to overflow the stack.

On a somewhat related note, I've been looking at Erlang lately, a strictly functional programming language, and one for which all variables can be set once but are immutable thereafter. Erlang, like many functional languages (LISP, Haskell, Eiffel, F#, etc.) does a lot with recursive functions. Further, if they are tail recursive, the Erlang compiler turns the recursive call sequence into a loop, thereby preventing stack overflow.
 
  • #27
Mark44 said:
@WWGD wanted to cobble together something that was recursive
I don't thing he meant "recursive" in the sense of "a function that repeatedly calls itself again with different arguments". Or if he did, that's certainly not what his function #3 does.
 
  • #28
Mark44 said:
if they are tail recursive, the Erlang compiler turns the recursive call sequence into a loop, thereby preventing stack overflow.
Yes, this is a key feature that Python (at least currently) lacks (although I have seen bytecode hacks from third parties that implement it--not something anyone should use in production, but they show that it would be possible with Python's virtual machine model), and which enables recursive algorithms to be used much more widely in languages that support it.
 
  • #29
PeterDonis said:
I don't thing he meant "recursive" in the sense of "a function that repeatedly calls itself again with different arguments".
I don't know of any definitions of this term that are different from what you described.
 
  • #30
Mark44 said:
I don't know of any definitions of this term that are different from what you described.
There aren't any other generally used ones that I'm aware of. I just don't think the OP is familiar with the generally used definition and was using it idiosyncratically, to mean something like "an algorithm that repeats the same steps many times with different parameters".
 
  • Like
Likes Mark44
  • #31
At any rate:
A simpler than the one I was thinking about:
Python:
#Is string a Palindrome, i.e., does it read the same left-right than right-left
def pal(x):
  string = str(x)
  if string ==string[:: -1]:
    print('yes, a pal')
 else:
   print(not a pal')
Still working on others. Gave up idea of recursion for this one.
 
Last edited:
  • #32
PeterDonis said:
For the OP's benefit, the theoretical advantage of this is that the algorithm will only be O(n), whereas the algorithm "reverse the string and then compare the reversed string with the original" is O(n^2) (since both the reversing and the comparing operations are O(n)).
## \mathcal{O}(n) + \mathcal{O}(n) = \mathcal{O}(n) \ne \mathcal{O}(n^2) ##, however there is obviously a linear gain in both time and space for an in-place check.
 
  • #33
pbuk said:
## \mathcal{O}(n) + \mathcal{O}(n) = \mathcal{O}(n) \ne \mathcal{O}(n^2) ##, however there is obviously a linear gain in both time and space for an in-place check.
Oh, yes, you're right.
 
  • #34
WWGD said:
A simpler than the one I was thinking about
Yes, but what about strings that represent negative numbers?
 
  • Like
Likes pbuk
  • #35
PeterDonis said:
Yes, but what about strings that represent negative numbers?
And if you are going to handle numbers, be careful with e.g. 12343210. This is why we have unit testing (another reason why playing with the REPL or Jupyter notebook is not "real" programming).
 

Similar threads

  • Programming and Computer Science
Replies
17
Views
1K
  • Programming and Computer Science
Replies
2
Views
1K
  • Programming and Computer Science
Replies
5
Views
3K
  • Programming and Computer Science
Replies
3
Views
2K
  • Programming and Computer Science
Replies
3
Views
2K
  • Programming and Computer Science
Replies
3
Views
1K
  • Programming and Computer Science
Replies
1
Views
1K
  • Programming and Computer Science
Replies
3
Views
2K
  • Programming and Computer Science
Replies
1
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
10
Views
1K
Back
Top