Recursion: Palindromes [duplicate] - python-3.x

This question already has answers here:
Recursive Function palindrome in Python [closed]
(10 answers)
Closed 7 years ago.
So I have this code for detecting if a string is a palindrome (the same forward and backwards) and I'm not sure how to change it to a recursive program
def isPalindrome(string):
i = 0
j = len(string) - 1
k = 0
while (i <= j):
if string[j] != string[i]:
k = 1
else:
i += 1
j -= 1
if k == 0:
return True
else:
return False
def main():
print("This program tests if strings are palindromes.")
word = input("Enter a string: ")
while word != "quit" :
if isPalindrome(word) == True:
print(word,"is a palindrome.")
else:
print(word,"is not a palindrome.")
word = input("Enter a string: ")
main()
I'm really bad with recursions and I don't really understand them any help would be great. Thanks

Without Recursion:
Ideally you might not need recursion for palindrome detection. It can be done simply as below.
def is_palindrome(word):
if word=="".join(reversed(word)):
return True
return False
Another shorter method
def is_palindrome(word):
return word[::-1]==word
Using Recursions:
For some reasons if you still require recursion and comfortable with arrays and indices, Use it like this.
def is_palindrome(word, end=0, start=0):
if end == 0:
end = len(word)-1
if start >= end:
return True
if word[start] != word[end]:
return False
start = start+1
end = end-1
return is_palindrome(start, end, word)
word = 'ramar'
print (is_palindrome(word))
This will be more Pythonic way with recursion
def is_palindrome(word):
if not word:
return True
else:
return word[0]==word[-1] and is_palindrome(word[1:-1])

Related

How to create a perfect number function using lists

My perfect number function is not working as intended :(. It prints false even though it should print true :(
def perfect_check(number):
z = []
for i in range(1, number):
if number % i == 0:
z.append(i)
if sum(z) == number:
return True
else:
return False
print(perfect_check(6))
def perfect_check(number):
z = []
for i in range(1, number):
if number % i == 0:
z.append(i)
if sum(z) == number:
return True
else:
return False
print(perfect_check(6))
You have put the if-else statement inside your for loop. It should be outside the for loop. Then, your code will work correctly.

Checking if a number is palindrome

I have this code for checking if a number is a palindrome and for some reason it returns false for number=1 even though it is palindrome. Why is that? The code works for other cases such as 12321.
def palindrome_integer(number):
if number != int:
return False
elif str(number) == str(number)[::-1]:
return True
else:
return False
If you want to check if number is integer, you should use isistance.
def palindrome_integer(number):
if not isinstance(number, int):
return False
elif str(number) == str(number)[::-1]:
return True
else:
return False
The rest of your code seems to work fine.
One-liner:
return isinstance(n, int) and str(n) == str(n)[::-1]
Or slightly more contrived:
import re
x = str(n)
return re.match(r”\d+“, x) and x == x[::-1]
solution without string
def palindrome_integer(num):
copy = num
rev = 0
while num!= 0:
rev = rev*10+num%10
num = num//10
return rev == copy
def palindrome_integer(number):
return type(number) == int and str(number)[::-1] == str(number)
Don't hesitate to comment if you have problem in understanding the solution.

Create a list that returns only palindromes from a list of numbers

I'm working on creating a program that will first check if numbers in the list are palindromes and then prints out only the palindromes. I am new to Python so I'm not sure how to properly append these to a new list.
inp= input()
list1 = []
while int(inp) != 0:
list1.append(inp)
inp= input()
def isPalindrome(N):
str1 = "" + str(N)
len1 = len(str1)
for i in range(int(len1 / 2)):
if (str1[i] != str1[len1 - 1 - i]):
return False
return True
list2 = []
for i in list1:
if i == isPalindrome:
list2.append(i(list1))
print(list2)
For example,
Input:
99
23
45
1221
0
Output:
99 1221
You just have some syntax errors in your code but your logic is correct..
Here is what you intended to do,
inp= int(input())
list1 = []
while inp != 0:
list1.append(inp)
inp = int(input())
def isPalindrome(N):
str1 = "" + str(N)
len1 = len(str1)
for i in range(int(len1 / 2)):
if (str1[i] != str1[len1 - 1 - i]):
return False
return True
list2 = []
for i in list1:
if isPalindrome(i):
list2.append(i)
print(list2)
Also if you want to make your program much shorter than i recommend this,
def isPalindrome(N):
str1 = str(N)
if str1[::-1] == str1:
return True
else:
return False
Just a slight change in synatx but logic is though same as yours. It uses string slicing in reverse direction.
Also i have type casted the input to integers using int(input()) as you said you need numbers to be printed in list2, if you don't want integers then just replace all int(input()) with input() and change your if condition to int(inp)!=0 at beginning

I want to return control to it starting point using function in a class in Python 3

I have 3 different functions in a class if the command in any of the function returns false, I want the program to begin all over again the way it started if the function that returns false was the last command among the function. Also, I want the program to return to the last successful function command if the failed command is not the last among the functions
When I run the program and last function command fails, the program returned to the starting point but ignore certain and crucial part of what I want to achieve, rather it full execute the second function command
class Test():
def greeting(self):
user_input = input("Greeting: ")
print("This is the greeting function")
list1 = ["hello", "Hi"]
if user_input in list1:
print("Thats good")
Test.cities(self)
elif user_input not in list1:
print("Mtchewwww")
Test.greeting(self)
else:
print("be serious")
def cities(self):
print("U re now inside the city function")
list2 = ["Otukpo", "Gboko"]
user_input = input("Cities: ")
if user_input in list2:
print("Nice one")
Test.num(self)
else:
print("that's not a city")
Test.cities(self)
def num(self):
user_input = input("Numbers: ")
list3 = [1, 2, 3, 4]
if int(user_input) in list3:
print("good number")
elif user_input not in list3:
print("That was bad")
Test.greeting(self)
else:
print("Can not compute")
calling = Test()
cal = calling.greeting
cal()
I want the program to behave like this:
if item is in list1 move to the next function but if not in list, try the current function again 3 times and after the the 3 chances and it's still not in the list return to the previous function
def greeting():
user_input = input("Greeting: ")
# It is not good to name your variables like `list1`, `str2`...
# plus, if your list is immutable, use a tuple instead.
options = ('hello', 'Hi')
if user_input in options:
print("That's good")
return True
else:
return False
def cities():
user_input = input("Cities: ")
options = ("Otukpo", "Gboko")
if user_input in options:
print("Nice one")
return True
else:
print("That's not a city")
return False
def num():
user_input = input("Numbers: ")
options = (1, 2, 3, 4)
try:
if int(user_input) in options:
print("Good number")
return True
else:
return False
except ValueError:
# In case that the input is not a number
return False
def main():
fns = (greeting, cities, num)
ptr = 0
cnt = 0
# Just for your information, you don't have to use `ptr >= 0 and ptr <3` in python
while 0 <= ptr < 3:
# print(ptr, cnt)
if cnt >= 3:
# if failed for 3 times, move `ptr` to the previous function, and reset `cnt` to 0
ptr -= 1
cnt = 0
continue
# Get the current function, as `fn`
fn = fns[ptr]
if fn():
# if the current function is a success, move to next, and reset `cnt`
ptr += 1
cnt = 0
else:
# if the current function is a failure, it will be tried again in next while loop
cnt += 1
main()
Use a pointer ptr to iterate over your three functions, and use a variable cnt to limit the failure times. Just try it.
Have fun with python!

Siimple Python. Not sure why my program is outputting this

I am making a program to take in a sentence, convert each word to pig latin, and then spit it back out as a sentence. I have no idea where I have messed up. I input a sentence and run it and it says
built-in method lower of str object at 0x03547D40
s = input("Input an English sentence: ")
s = s[:-1]
string = s.lower
vStr = ("a","e","i","o","u")
def findFirstVowel(word):
for index in range(len(word)):
if word[index] in vStr:
return index
return -1
def translateWord():
if(vowel == -1) or (vowel == 0):
end = (word + "ay")
else:
end = (word[vowel:] + word[:vowel]+ "ay")
def pigLatinTranslator(string):
for word in string:
vowel = findFirstVowel(word)
translateWord(vowel)
return
print (string)
You have used the lower method incorrectly.
You should use it like this string = s.lower().
The parentheses change everything. When you don't use it, Python returns an object.
Built-in function should always use ()
Here is the corrected version of the code which should work:
s = input("Input an English sentence: \n").strip()
string = s.lower() #lowercasing
vStr = ("a","e","i","o","u")
def findFirstVowel(word):
for idx,chr in enumerate(word):
if chr in vStr:
return idx
return -1
def translateWord(vowel, word):
if(vowel == -1) or (vowel == 0):
end = (word + "ay")
else:
end = (word[vowel:] + word[:vowel]+ "ay")
def pigLatinTranslator(string):
for word in string:
vowel = findFirstVowel(word)
translateWord(vowel,word)
return
print(string)

Resources