Palindrome logic in python: What is wrong with this program? - python

def isPalindrome(word):
l = len(word)
for i in range(l/2):
if(word[i] != word[i+l-1]):
return 0
return 1
def main():
print("\n\n\tTo Check if the word is a Palindrome\n\n")
word = raw_input("Enter a word : ")
if(isPalindrome(word) == 1):
print("It is a Palindrome")
elif:
print("It is not a Palindrome")
main()
In my opinion everything is right in the program. It goes good when I enter a word which is not a palindrome but when I enter a palindrome it gives an error like this:
Enter a word : madam
Traceback (most recent call last):
File "temp.py", line 16, in <module>
File "temp.py", line 6, in isPalindrome
IndexError: string index out of range

First thing that is wrong is: elif: - if you're using else-if you should provide a condition, the fix in this case it to change it to else:
Second, the if should be: if(word[i] != word[l-i-1]): in order for the function to work (check that each letter is equal to its equivalent in the word).
Third, less critical but still important: keep the styling:
remove redundant braces
use proper naming convention (snake-case - not camel-case)
use True/False as return values instead of 1/0
use floor division // (as AChampion mentioned in the comments)
Complete code (fixed):
def is_palindrome(word):
l = len(word)
for i in range(l//2):
if word[i] != word[l-i-1]:
return False
return True
def main():
print("\n\n\tTo Check if the word is a Palindrome\n\n")
word = raw_input("Enter a word : ")
if is_palindrome(word):
print("It is a Palindrome")
else:
print("It is not a Palindrome")
if __name__ == "__main__":
main()

Your logic for checking palindrome should be:
if(word[i] != word[l-1-i]):
return 0
It's okay to do l/2 if you're on python 2 but python 3 will produce the result as a floating point value.
Your code seems to be in py3.
And you need to give a condition to the elif block. Otherwise, change it to else.

Change word[i+l-1] to word[l-i-1]:
def isPalindrome(word):
l = len(word)
for i in range(l // 2):
if(word[i] != word[l-i-1]):
return 0
return 1
The goal is to get the word[l-i-1 to count down while i is counting up; hence, you need to subtract i rather than add it.
Also, I would change the l/2 to l // 2 so that it works in Python 3 as well.
Hope that helps :-)

You should round the l/2 value
def isPalindrome(word):
l = len(word)
for i in range(round(l/2)):
if(word[i] != word[i+l-1]):
return 0
return 1
print("\n\n\tTo Check if the word is a Palindrome\n\n")
word = input("Enter a word : ")
if(isPalindrome(word) == 1):
print("It is a Palindrome")
else:
print("It is not a Palindrome")

Related

Name 'USER_INPUT' is not defined? (Python 3.9.2)

I'm trying to make a Python program which takes in a string and evaluates whether it's a palindrome (reads the same backwards) or not. I've tried to extend it by not allowing numbers to come as an input, and that part works fine.
a = eval(input('Put a word here: '))
if type(a) == int or float:
print('That\'s a number man.')
exit()
b = a[::-1]
if a == b:
print('The word is a palindrome!')
else:
print('The word is not a palindrome!')
However, when I run the program with a random word, such as 'fries', as an input in cmd (using Windows, Python 3.9.2), I get this error:
Traceback (most recent call last):
File "C:\Users\Azelide\Desktop\folderr\hello.py", line 1, in <module>
a = eval(input('Put a word here: '))
File "<string>", line 1, in <module>
NameError: name 'fries' is not defined
I've seen people getting this error when running Python 2 and using input() instead of raw_input(), that should not be a problem in Python 3 though. By the way, when I omit the part of the code which excludes numbers from the input, the palindrome checker works fine. Any ideas?
As mentioned in the comments, your first condition always evaluates to true
try this:
a = input('Put a word here: ')
for char in a:
if char.isdigit():
print('That\'s a number man.')
exit()
b = a[::-1]
if a == b:
print('The word is a palindrome!')
else:
print('The word is not a palindrome!')
output:
Put a word here: fries
The word is not a palindrome!
I have managed to solve it now, while extending it to not allow number-letter combinations.
a = input('Put a word here: ')
try:
float(a)
print('That\'s a number man.')
exit()
except ValueError:
for char in a:
if char.isdigit():
print('That\'s a combination of letters and numbers.')
exit()
b = a[::-1]
if a == b:
print('The word is a palindrome!')
else:
print('The word is not a palindrome!')
I will tell you what is wrong in your code the function eval takes a string so that if the string could be a function it will make the function else it will raise error and when you made the function input inside it, this returns a value if this value == a function then make the function else raise error like this
a = eval(input('enter a name: '))
now if the user enters a value which can not be a function it will raise error like this
name'value that the user input' is not defined
now you can make as what the people said up
a = input('Put a word here: ')
try:
float(a)
print('That\'s a number man.')
exit()
except ValueError:
for char in a:
if char.isdigit():
print('That\'s a combination of letters and numbers.')
exit()
b = a[::-1]
if a == b:
print('The word is a palindrome!')
else:
print('The word is not a palindrome!')

How can I make sure a word is palindrome using Python while using recursion?

I am trying to create a code in which python asks the user for input or a word and it has to check whether it's a palindrome or not using recursion. If the word is not a palindrome through the reverse() function it will take in the string and, through recursion, return that string in reverse. It seems that I am able to take input and when I put in a word that's not a palindrome it gives me back the output needed. However it doesn't give back the word in reverse and also when I put a word that is a palindrome and it doesn't give the input back leaving a blank space in the output.
def reverse(choice, index, new_word):
if index < 0:
return new_word
else:
new_word += choice[index]
return reverse (choice, index - 1, new_word)
def palindrome():
new_word = ""
choice = input("Please enter a word to check if it is palindrome:")
result = reverse(choice, len(choice) - 1, new_word)
if result == choice:
print("That word",choice,"IS a palindrome")
else:
print("Sorry,",new_word,"is NOT a palindrome")
palindrome()
This is happening because you have set new_word to an empty string, and then you're taking the result of reverse() and storing that in another variable called result.
This should fix your issue:
def palindrome():
new_word = ""
choice = input("Please enter a word to check if it is palindrome:")
result = reverse(choice, len(choice) - 1, new_word)
if result == choice:
print("That word",choice,"IS a palindrome")
else:
# change here to result
print("Sorry,",result,"is NOT a palindrome")
Alternatively, you can use choice[::-1] to reverse a string. it is cleaner and you don't have to use recursion. However, the above fix will help you with the recursion bit as well.
Try the following:
def check_palindrome(word): # Creating function with 1 parameter: word
if word == word[:: -1]: # word[:: -1] reverses a string
return True # Return a true value if word is the same when reversed
else:
return False # Otherwise, return a false value
print(check_palindrome("racecar")) # Palindrome
print(check_palindrome("hello world")) # Not a palindrome
the syntax word[:: -1] reverses the word.

How do I get my code to repeat in a loop?

str = input("Enter the String")
l = len(str)
p = l-1
index = 0
while index < p:
if str[index] == str[p]:
index = index + 1
p = p-1
print("String is a Palindrome")
break
else:
print("String is not a Palindrome")
break
i need this to be able to ask the user if they would like to repeat the process or not but i cant figure it out because every time i try it only repeats the string "string is not a palindrome"
Are you looking for this:
while True:
user_input = input("Enter the String")
l = len(user_input)
p = l-1
index = 0
while index < p:
if user_input[index] == user_input[p]:
index = index + 1
p = p-1
print("String is a Palindrome")
break
else:
print("String is not a Palindrome")
break
gonext = input("continue?(no to exit) ")
if gonext == "no":
break
elif gonext == "yes":
continue
add a input and if statement to ask the user, and while True to repeat.
and str is a built-in from Python, so don't use it as variable name.
If you want your code to be able to repeat any task, you need to wrap it into a loop. Also you shouldn't use str as a name for a variable, because that name is used in python to create a new string.
one possible solution would be
repeat = True
while repeat:
# your code
repeat = input("repeat? (y for yes, everything else is tretaed as no)\n") == "y"
Further, I want to point out, that your code is not doing what you expect.
A palindrome is defined as a String which reads backwards the same as forwards.
In your code, you are actually just testing whether the first and last character are the same. In the if branch, the problem is not solved. The positive result can only be given at the end of the loop.
Also, you don't cover the empty string (no output at all), which I would consider as a palindrome.
some cases you could test:
ada -> correct positive
asd -> correct negative
asda -> false positive
"" -> nothing at all
-a[arbitray string]a -> positive?
A correct implementation of the palindrome check would be something like this:
user_input = input("Enter the String\n")
isPalindrome = True
for i in range(len(user_input)//2): # check till center from both ends
if user_input[i] != user_input[-i-1]: # index -1 is last character
isPalindrome = False
break
if isPalindrome:
print("String is a Palindrome")
else:
print("String is not a Palindrome")

Check for a palindrome in python

palindrome
Here is the code i have written so far:
string=input(("Enter a string:"))
for char in string:
print(char)
if(string==string[::-1]):
print("The string is a palindrome")
else:
print("Not a palindrome")
To produce the described output, it looks like you'd need to perform character-wise comparison. What you've attempted is a straight-forward comparison of a string with it's reverse. Try this:
string=input(("Enter a string:"))
rev_string = string[::-1]
for i in range(len(string)):
print (string[i], "--", rev_string[i])
if string[i].lower() != rev_string[i].lower():
print("Not a palindrome")
exit(0)
print("The string is a palindrome")
I would like to point out that checking if two characters are the same is not trivial, as discussed in this answer. The following code should work for any character:
import unicodedata
def normalize_caseless(text):
return unicodedata.normalize("NFKD", text.casefold())
def caseless_equal(left, right):
return normalize_caseless(left) == normalize_caseless(right)
string = input("Enter a string: ")
rev_string = string[::-1]
i = 0
palindrome = True
while palindrome and i < len(string):
print(f'{string[i]} -- {rev_string[i]}')
palindrome = caseless_equal(string[i], rev_string[i])
i += 1
print(f"The string is{' not'*(not palindrome)} a palindrome")

Where's the bug in this function to check for palindrome?

Given below is the code to check if a list is a palindrome or not. It is giving correct output for 983. Where am I going wrong?
def palindrome(num):
flag=0
r=num[::-1]
for i in range (0, len(num)-1):
if(r[i]==num[i]):
flag=1
else:
flag=0
return flag
You should return as soon as there is a mismatch. Also, you just need to iterate till half the length:
def function(...):
...
for i in range (0, (len(num) + 1) / 2):
if r[i] != num[i]:
return False
return True
BTW, you don't need that loop. You can simply do:
def palindrome(num):
return num == num[::-1]
This would be easier:
def palindrome(num):
if num[::-1] == num:
return True
else:
return False
Your for loop checks all pairs of characters, no matter if it found mismatch or not. So, in case of string '38113' it will return True, because the flag variable will be set to True after the check for equality of last digit in '38113' and its reversed version '31183' (both equal to 3, while the string isn't a palindrome).
So, you need to return False right after you've found mismatch; if you checked all the characters and didn't find it - then return True, like so:
def palindrome(num):
r = num[::-1]
for i in range (0, len(num)-1):
if(r[i] != num[i]):
return False
return True
Also, as someone pointed out it'll be better to use python's slices - check out the documentation.
Just for the record, and for the ones looking for a more algorithmic way to validate if a given string is palindrome, two ways to achieve the same (using while and for loops):
def is_palindrome(word):
letters = list(word)
is_palindrome = True
i = 0
while len(letters) > 0 and is_palindrome:
if letters[0] != letters[-1]:
is_palindrome = False
else:
letters.pop(0)
if len(letters) > 0:
letters.pop(-1)
return is_palindrome
And....the second one:
def is_palindrome(word):
letters = list(word)
is_palindrome = True
for letter in letters:
if letter == letters[-1]:
letters.pop(-1)
else:
is_palindrome = False
break
return is_palindrome
str1=str(input('enter string:'))
save=str1
revstr=str1[::-1]
if save==revstr:
print("string is pailandrom")
else:
print("not pailadrom")
# We are taking input from the user.
# Then in the function we are reversing the input i.e a using
# slice [::-1] and
# storing in b
# It is palindrome if both a and b are same.
a = raw_input("Enter to check palindrome:")
def palin():
#Extended Slices to reverse order.
b = a[::-1]
if a == b:
print "%s is palindrome" %a
else:
print "%s is not palindrome" %a
palin()
this would be much easier:
def palindrome(num):
a=num[::-1]
if num==a:
print (num,"is palindrome")
else:
print (num,"is not palindrome")
x=input("Enter to check palindrome:")
palindrome(x)
Here in my opinion is the most elegant:
def is_palindrome(s):
if s != '':
if s[0] != s[-1]:
return False
return is_palindrome(s[1:-1])
return True
it's also the same code in the is_palindrome() function:
pip install is-palindrome
>>> from is_palindrome import is_palindrome
>>> x = "sitonapanotis"
>>> y = is_palindrome(x)
>>> y
True
Take care to note the hyphen vs underscore when installing vs. importing
a="mom"
b='mom'[::-1] # reverse the string
if a==b: # if original string equals to reversed
print ("palindrome ")
else:
print ("not a palindrome ")
def palindrome(a):
a=raw_input('Enter :')
b=a[::-1]
return a==b

Categories