Python reverse() for palindromes - python

I'm just getting started in python, and I'm trying to test a user-entered string as a palindrome. My code is:
x=input('Please insert a word')
y=reversed(x)
if x==y:
print('Is a palindrome')
else:
print('Is not a palindrome')
This always returns false because y becomes something like <reversed object at 0x00E16EF0> instead of the reversed string.
What am I being ignorant about? How would you go about coding this problem?

Try y = x[::-1]. This uses splicing to get the reverse of the string.
reversed(x) returns an iterator for looping over the characters in the string in reverse order, not a string you can directly compare to x.

reversed returns an iterator, which you can make into a string using the join method:
y = ''.join(reversed(x))

For future reference, a lambda from the answers above for quick palindrome check:
isPali = lambda num: str(num) == str(num)[::-1]
example use:
isPali(9009) #returns True

Try this code.
def pal(name):
sto_1 = []
for i in name:
sto_1.append(i)
sto_2 = []
for i in sto_1[::-1]:
sto_2.append(i)
for i in range(len(name)):
if sto_1[i] == sto_2[i]:
return "".join(sto_1), "".join(sto_2)
else:
return "no luck"
name = raw_input("Enter the word :")
print pal(name)

list(reverse( mystring )) == list( mystring )
or in the case of numbers
list(reverse( str(mystring) )) == list( str(mystring) )

Try this code:
def palindrome(string):
i = 0
while i < len(string):
if string[i] != string[(len(string) - 1) - i]:
return False
i += 1
return True
print palindrome("hannah")

Try this code to find whether original & reverse are same or not:-
if a == a[::-1]:
#this will reverse the given string, eventually will give you idea if the given string is palindrome or not.

Related

I wished to check if an input is in the string and then print the output

I intended to let the program check if the input matches with any character in a str and then print out the result, the player input and the underscores in the correct places. This is my test code so far:
astring = "apple"
bstring = "_ " * 5
print(bstring)
my_input = input("enter a letter")
for i, n in enumerate(astring):
if my_input == i:
bstring[n] = my_input
else:
i = i + 1
print(bstring)
However, only the underscores are being printed out. Can anyone help me?
In your loop, you should be checking to see if the letter at your current index of your string is the same as the letter at the current index of your input string, to do this you can use:
if i < len(my_input) and my_input[i] == n:
Also, strings in Python are immutable, and so you can't change them via index. Instead, use an array of _, so that you can change what is at a particular index. Then, at the end, join each element in your list by a space.
Lastly, there is no need to increment i, as this is done for you by your for loop:
astring='apple'
bstring=['_']*len(astring)
print(bstring)
my_input = input('enter a letter')
for i,n in enumerate(astring):
if i < len(my_input) and my_input[i] == n:
bstring[i] = n
print(' '.join(bstring))
for i,n in enumerate(astring):
'i' is the index, 'n' is the character. You have it the other way around in 'if'.
hope it will help you
astring='apple'
bstring=["_" for i in range(len(astring))]
print(bstring)
my_input=input('enter a letter')
for i,n in enumerate(astring):
if my_input==n:
bstring[i]=my_input
else:
i=i+1
print(*bstring)

How do I use for loops with functions for string input in python?

I'm having trouble with creating a function that takes an argument of a string and returns just the numbers in type str. My code looks something like this.:
def check_if_number(number_string):
for ch in number_string:
if ch.isdigit():
num = number_string[ch]
return num
print(check_if_number('1655t'), end='')
It should print: 1655
You should add each char to a string if it is a digit :
def check_if_number(number_string):
digit_string = ""
for ch in number_string:
if ch.isdigit():
digit_string += ch
return digit_string
print(check_if_number('1655t'))
# 1655
Note that you can also use the re library :
import re
re.sub("\D", "", "1655t")
#1655
This code replace every non-digit character (matched by \D) by an empty string.
Have a look at this question to find more way to do it
You can do this :
def check_if_number(number_string):
num = ""
for ix in number_string :
if ix.isdigit():
num += ix
return int(num)
This function will return 1655, if the input is 1655t. You return from the function once you scan the complete string and append all ints to a string.
The easy way would be just using filter and concatenating the filtered letters in the end:
def check_if_number(number_string):
return ''.join(filter(str.isdigit, number_string))
Assuming all numbers are together (i.e. No letters exist between digits like "1e234g7"),
def check_if_number(number_string):
num = ''
for ch in number_string:
if ch.isdigit():
num += ch
return num
print(check_if_number('1655t'), end='')
This will return a string that only has digits in it. If you want to return a type int, then simply do return int(num).
If you want to take floats into account as well:
def check_if_number(number_string):
num = ''
for ch in number_string:
if ch == '.' or ch.isdigit():
num += ch
return num
print(check_if_number('1655t'), end='')
Similarly, this will return a string. If you want type float, simply do return float(num).
I tried not to deviate too much from what you already had... I hope this helps.
I'm uncertain what check_leap_year() function is so I just commented it out and called the function you gave us instead.
When you pass anything into a function in order to manipulate it and spit it back out different than it came in you should create a new variable for the changed data set.
In this case I used num = ""
By initiating an empty string inside of the function I can now add the data that pass my condition to that new, empty string.
isdigit() returns a boolean. So instead of using if x.isdigit: get in the habit of checking the boolean. Try if x.isdigit() is True instead.
Return your finished new string AFTER it is finished. Make sure your return statement is indented correctly or you are only going to return one number instead of all of them. The return should be outside of the loop so that it will only return once the loop is done.
num_string = "1a2s3d4f5g666hhh777jjj888kkk9l0"
def check_if_number(number_string):
num = ""
for ch in number_string:
if ch.isdigit() is True:
num += ch
return num
print(check_if_number(num_string))
Output:
>>> 1234566677788890

Improving Python Palindrome code

So I recently implemented a code that checks a word to see if it's a palindrome.
def isPalindrome():
string = input('Enter a string: ')
string1 = string[::-1]
if string[0] == string[(len(string)-1)] and string[1:(len(string)-2)] == string1[1:(len(string)-2)]:
print('It is a palindrome')
else:
print('It is not a palindrome')
isPalindrome()
I was wondering if anyone could give me tips on simplifying the code.
Edit - If I were to make the function an iterative function with the statements string == string1, how would I stop the endless while loop? Would I need a count to stop the while loop?
No need for such complex conditional. You already have a reversed string (string[::-1]).
All you need to do is this:
def isPalindrome():
string1 = input('Enter a string: ')
string2 = string1[::-1]
if string1 == string2:
return 'It is a palindrome'
return 'It is not a palindrome'
isPalindrome()
(by the way don't use string as a variable name. That's the name of a built-in module)
It's better to return the strings instead of printing them. That way your function will not return None (preventing some stuff that could happen later)
You can do it in a one liner:
return "Is a palindrome" if string == string[::-1] else "Not a palindrome"
Sample script:
>>> string = "stanleyyelnats"
>>> print "Is a Palindrome" if string == string[::-1] else "Not a palindrome"
>>> Is a Palindrome
You can also do this (although its slower):
print "Is a Palindrome" if string == ''.join(reversed(string)) else "Not a palindrome"
Also, use raw_input and not input. Because input will be evaluated. Let me show you an example:
Script
inp = input("Evaluate ")
print inp
Run
Evaluate "cheese" + "cake"
cheesecake
Here is a simple solution in just 1 LINE.
plandrom = lambda string: True if string == string[::-1] else False
Please check this algorithm,
def is_palindrome(n):
m = len(n)/2
for i in range(m):
j = i + 1
if n[i] != n[-j]:
return False
return True
print is_palindrome('malayayalam')
So, I just got into learning python and I have been trying to these exercises, #8. Though I see that a lot of these answers are creating a new reverse string(which adds a memory overhead) and comparing both strings, I thought I could utilize lesser memory by doing this:
def is_palindrome(s):
l=len(s)
list_s=list(s)
for i in range(0,l):
if(list_s[i] !=list_s[l-i-1]):
return False
else:
return True
You can use a print statement to verify.
All I am doing is comparing the first index to the last and the second index to the second last and so on.
Hope that helps.
Check Counter from collections
from collections import Counter
def is_palindrome(letters):
return len([v for v in Counter(letters).values() if v % 2]) <= 1
Here is another solution I came up with:
###Piece of code to find the palindrome####
def palindrome():
Palindromee = input("Enter the palindrome \t:")
index = 0
length = len(Palindromee)
while index < length:
if Palindromee[0] == Palindromee[-1] :
index +=1
print ("Palindrome worked as expected")
palindrome()
Simple way to write palindrome
a=raw_input("Enter the string : ") # Ask user input
b= list(a) # convert the input into a list
print list(a)
b.reverse() # reverse function to reverse the
# elements of a list
print b
if list(a) == b: # comparing the list of input with b
print("It is a palindrome")
else:
print("It is not a palindrome")
we could use reverse String function to verify Palindrome:
def palindrome(s):
str=s[::-1]
if s==str:
return True
else:
return False
palindrome('madam')
you can as well try this
def palindrome(str1):
return str1==str1[::-1]
print(palindrome(str1)
the answer above returns a boolean according to the string given
if it is a palindrome prints true else false

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

How to check whether a str(variable) is empty or not?

How do I make a:
if str(variable) == [contains text]:
condition?
(or something, because I am pretty sure that what I just wrote is completely wrong)
I am sort of trying to check if a random.choice from my list is ["",] (blank) or contains ["text",].
You could just compare your string to the empty string:
if variable != "":
etc.
But you can abbreviate that as follows:
if variable:
etc.
Explanation: An if actually works by computing a value for the logical expression you give it: True or False. If you simply use a variable name (or a literal string like "hello") instead of a logical test, the rule is: An empty string counts as False, all other strings count as True. Empty lists and the number zero also count as false, and most other things count as true.
The "Pythonic" way to check if a string is empty is:
import random
variable = random.choice(l)
if variable:
# got a non-empty string
else:
# got an empty string
Just say if s or if not s. As in
s = ''
if not s:
print 'not', s
So in your specific example, if I understand it correctly...
>>> import random
>>> l = ['', 'foo', '', 'bar']
>>> def default_str(l):
... s = random.choice(l)
... if not s:
... print 'default'
... else:
... print s
...
>>> default_str(l)
default
>>> default_str(l)
default
>>> default_str(l)
bar
>>> default_str(l)
default
Empty strings are False by default:
>>> if not "":
... print("empty")
...
empty
For python 3, you can use bool()
>>> bool(None)
False
>>> bool("")
False
>>> bool("a")
True
>>> bool("ab")
True
>>> bool("9")
True
Some time we have more spaces in between quotes, then use this approach
a = " "
>>> bool(a)
True
>>> bool(a.strip())
False
if not a.strip():
print("String is empty")
else:
print("String is not empty")
element = random.choice(myList)
if element:
# element contains text
else:
# element is empty ''
How do i make an: if str(variable) == [contains text]: condition?
Perhaps the most direct way is:
if str(variable) != '':
# ...
Note that the if not ... solutions test the opposite condition.
if the variable contains text then:
len(variable) != 0
of it does not
len(variable) == 0
use "not" in if-else
x = input()
if not x:
print("Value is not entered")
else:
print("Value is entered")
{
test_str1 = ""
test_str2 = " "
# checking if string is empty
print ("The zero length string without spaces is empty ? : ", end = "")
if(len(test_str1) == 0):
print ("Yes")
else :
print ("No")
# prints No
print ("The zero length string with just spaces is empty ? : ", end = "")
if(len(test_str2) == 0):
print ("Yes")
else :
print ("No")
}
string = "TEST"
try:
if str(string):
print "good string"
except NameError:
print "bad string"
Python strings are immutable and hence have more complex handling when talking about its operations. Note that a string with spaces is actually an empty string but has a non-zero size.
Let’s see two different methods of checking if string is empty or not:
Method #1 : Using Len()
Using Len() is the most generic method to check for zero-length string. Even though it ignores the fact that a string with just spaces also should be practically considered as an empty string even its non-zero.
Method #2 : Using not
Not operator can also perform the task similar to Len(), and checks for 0 length string, but same as the above, it considers the string with just spaces also to be non-empty, which should not practically be true.
Good Luck!
#empty variable
myvar = ""
#check if variable is empty
if not myvar:
print("variable is empty") # variable is empty

Categories