Python Forum
Palindrome in Python - result always false
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Palindrome in Python - result always false
#11
(Oct-16-2019, 12:40 PM)perfringo Wrote:
(Oct-16-2019, 12:18 PM)RavCOder Wrote: I didn't understand exactly.
What do you mean with all cases?
And how should I set my conditions for testing?

You could extend your function so that it returns True for following palindromes:


>>> def is_palindrome(word):
...     word_start = ''
...     for letter in word:
...         word_start = letter + word_start
...         if word == word_start:
...             return True
...   
...     return False
... 
>>> is_palindrome('Hannah')
False
>>> is_palindrome('Was it a car or a cat I saw?')
False
One way of doing it is to 'clean string' (convert all lowercase, remove spaces and punctuation) and only after that make the comparison.

Something along those lines:

>>> import string
>>> def is_palindrome(text):
...     cleaned = [letter.lower() for letter in ''.join(text.split()) if letter not in string.punctuation]
...     return all(forward == backward for forward, backward in zip(cleaned, reversed(cleaned))) 
... 
>>> is_palindrome('Was it a car or a cat I saw?')
True
>>> is_palindrome('Hannah')
True
>>> is_palindrome('better')
False


It's too complex for me what you did, I'm too stupid for that.
Not that your code is bad or anything, it's just me that I don't understand.
Reply
#12
If you are learning then you are beginner, not stupid.

Just to walk through:

Our objective can be set as: 'remove whitespaces and punctuation and find out whether remaining lowercase characters are same forward and backward'

'remove whitespaces':

''.join(text.split())
It splits string on whitespaces and then constructs new string without them. If there are no whitespaces returns new string which is same as the old one. For more type help(str.join) into interactive interpreter (press Q to quit help)

'remove punctuation':

if letter not in string.punctuation
Python has built-in module named string and punctuation contains following chars (one can define it's own punctuation list/string and check against that):

>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
'lowercase characters':

letter.lower()
For more information type help(str.lower) into interactive interpreter.

All these actions are put into list comprehension 'give me a lowercase letter for every letter in string without spaces which is not punctuation':

[letter.lower() for letter in ''.join(text.split()) if letter not in string.punctuation]
Now when we have cleaned the string (and have list instead of it) we test equality from both sides.

There is built-in function zip() which action can be described as putting iterable elements in parallel (or rows to columns or transpose):

>>> list(zip('abc', '123'))
[('a', '1'), ('b', '2'), ('c', '3')]
We create pairs using zip and checking for equality of pair items. We use tuple unpacking and give names forward/backwards to appropriate element (for better readability, it could be x, y or whatever). We use reversed() function to reverse list and get order which is backwards.

>>> word = 'better'                                   # first and last letters are not equal
>>> list(zip(word, reversed(word)))
[('b', 'r'), ('e', 'e'), ('t', 't'), ('t', 't'), ('e', 'e'), ('r', 'b')]
We use built-in function all() which has short-circuiting behaviour (first False terminate the loop). It returns True only if all comparisons return True (as name suggests :-).

all(forward == backward for forward, backward in zip(cleaned, reversed(cleaned)))
Lot of Python built-in stuff is used, but spoken algorithm and code have good parity (and this is one of advatages of Python)
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#13
(Oct-16-2019, 01:19 PM)perfringo Wrote: If you are learning then you are beginner, not stupid.

Just to walk through:

Our objective can be set as: 'remove whitespaces and punctuation and find out whether remaining lowercase characters are same forward and backward'

'remove whitespaces':

''.join(text.split())
It splits string on whitespaces and then constructs new string without them. If there are no whitespaces returns new string which is same as the old one. For more type help(str.join) into interactive interpreter (press Q to quit help)

'remove punctuation':

if letter not in string.punctuation
Python has built-in module named string and punctuation contains following chars (one can define it's own punctuation list/string and check against that):

>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
'lowercase characters':

letter.lower()
For more information type help(str.lower) into interactive interpreter.

All these actions are put into list comprehension 'give me a lowercase letter for every letter in string without spaces which is not punctuation':

[letter.lower() for letter in ''.join(text.split()) if letter not in string.punctuation]
Now when we have cleaned the string (and have list instead of it) we test equality from both sides.

There is built-in function zip() which action can be described as putting iterable elements in parallel (or rows to columns or transpose):

>>> list(zip('abc', '123'))
[('a', '1'), ('b', '2'), ('c', '3')]
We create pairs using zip and checking for equality of pair items. We use tuple unpacking and give names forward/backwards to appropriate element (for better readability, it could be x, y or whatever). We use reversed() function to reverse list and get order which is backwards.

We use built-in function all() which has short-circuiting behaviour (first False terminate the loop). It returns True only if all comparisons return True (as name suggests :-).

all(forward == backward for forward, backward in zip(cleaned, reversed(cleaned)))
Lot of Python built-in stuff is used, but spoken algorithm and code have good parity (and this is one of advatages of Python)


Thanks!!!
Now seems clearer to me than before, unfortunately as I have already said in my thread, I still don't have the most knowledge in Python and I don't know yet how to set certain logics of the exercises.
I know I have to do more exercises, but how can I do exercises if I can't even think about the solution?
Reply
#14
(Oct-16-2019, 01:27 PM)RavCOder Wrote: I know I have to do more exercises, but how can I do exercises if I can't even think about the solution?

One technique is to define you task in spoken language (what you must do to get required result). It's important that you think what (and not how) in this stage.

Like in this excercise 'remove whitespaces and punctuation and find out whether remaining lowercase characters are same forward and backward'

Now we start to break this down to smaller pieces and look for solutions in Python code:

- how remove whitespaces
- how to remove punctuation
- how to lowercase characters
- how to compare characters in string forward and backward

These are quite specific tasks and googling them (adding Python to the end) will give you a plenty of ideas how to solve them.

Without plan which is spelled out in spoken language it's (almost) impossible to code. And as you can observe: 'remove whitespaces and punctuation and find out whether remaining lowercase characters are same forward and backward' has nothing Python specific, this 'algorithm' can be used to solve this with paper and pencil. So find the solution to the problem and use whatever tools you have in your disposal :-).
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Simple Palindrome Inkanus 4 2,102 Nov-25-2020, 04:11 PM
Last Post: perfringo
  difference between «1 in [2] == False» and «(1 in [2]) == False» fbaldit 2 2,226 Apr-20-2020, 05:39 PM
Last Post: fbaldit
  Post JSON from python to PHP don't give expected result pgagnebin 1 3,737 Sep-04-2019, 10:29 PM
Last Post: micseydel
  python hmac gave different result than php hash_hmac nadavvin 2 3,159 Feb-18-2019, 03:35 PM
Last Post: nadavvin
  python result problem of an iteration algorithm for power allocation Jessica 1 2,622 Sep-07-2018, 08:08 PM
Last Post: micseydel
  python code (embedded in Redshift) to return result of the query Mel 0 2,449 Aug-24-2018, 06:12 PM
Last Post: Mel
  Palindrome mp3909 3 4,225 Oct-18-2017, 01:54 PM
Last Post: sparkz_alot

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020