def isPal(s):
if len(s) <= 1:
print(s)
else:
print(s)
s[0] == s[-1] and isPal((s[1:-1]))
print(s)
print("HI")
x = isPal("deleveled")
print(x)
Output:
deleveled
elevele
level
eve
v
HI
eve
HI
level
HI
elevele
HI
deleveled
HI
None
Let's break down the program.
Firstly, if the string given to isPal() is one or zero characters, it's printed. In other words, once we can't simplify any more, we stop simplifying and just output what we have.
Otherwise (when we have two or more characters), we check that the first and last character are equal, and then perform the same algorithm on the string without these two characters. This continues until we have one or zero characters, as described above.
The reason the word is rebuilding at the end is that you have printed the string again after your recursive function call. So after going 'deeper' into your word, you print where you came from too.
EDIT: The reason 'HI' is printed is that after you've done your going 'deeper' into the word and have come back out, you print 'HI' each time. So every time you take one step back out of the program (one more letter back at the start and end), you print 'HI'.
I think the issue with your code is that you've not actually told the function to answer the 'isPal' question with a True or False.
def isPal(s):
if len(s) <= 1:
print(s)
return True
else:
print(s)
return (s[0] == s[-1] and isPal((s[1:-1])))
x = isPal("deleveled")
print(x)
This code will now return True or False depending on whether your algorithm detects that the string is a palindrome or not.
Your code actually did what you wanted it to, you just hadn't returned the result of your check.
Related
I am trying to determine if a given word is a palindrome.
The goal of my code is that the function will take a word, and remove it of any punctuation or spaces. If the length of the word is 0 or 1, it is returned that the word is a palindrome. I then check if the first and last letter are the same. If they aren't, it is returned that it is not a palindrome. If they first and last letters the same, I then want to replace those two letters with spaces and call my function again. The reason I replace the letters with spaces is so that it will be edited by my initial edit statements.
def palindrome(word):
editWord = word.strip(" ").strip("!").strip("?")
stringOne = "A palindrome"
stringTwo = "Not a palindrome"
if len(editWord) == 0 or len(editWord) == 1:
return stringOne
elif editWord[0] != editWord[-1]:
return stringTwo
else:
word = editWord.replace(editWord[0], " ").replace(editWord[-1], " ")
palindrome(word)
return stringOne
print(palindrome("area"))
When tested with single letters it functions properly, as well if I test words like 'are' which obviously is not a palindrome. However, if I call the word area it returns "A palindrome" when it is not. This makes it seem like it is not calling my function again. Any suggestions on why this is happening?
For recursion to work properly here, your else statement should say something along the lines of "the word is a palindrome if the outer characters are equal and the remainder is also a palindrome". Instead, your code is replacing all occurrences of the outer characters with spaces, checking if the word is a palindrome, and ignoring the result to always return "yes".
You can do a proper recursion using slicing instead of replacement:
else:
return palindrome(editWord[1:-1])
Another alternative to replacing the letters while still doing this recursively to to keep track of the index in the word and increment it on recursion. This saves you from having to make new slices on each recursion. In this case your edge case will be when the index is in the middle of the word.
def palindrome(word, i = 0):
if i >= len(word)//2:
return True
if word[i] != word[-(i+1)]:
return False
return palindrome(word, i+1)
palindrome("mrowlatemymetalworm") # true
i try to find a recursive function that take two string and returns true if string1 is a substring of string2 and false otherwise by check recursively if str2 starts with str1.
i try this code but it does not work i do not know why !
def main():
s1 = input("enter string")
s2 = input("enter steing")
sub = subs(s1,s2)
print(sub)
def subs(s1, s2):
if s2 == 0:
return True
else:
if s2.startswith((s1)):
subs(s1, s2[1:])
return True
main()
thank you !
Your program has a few syntactic issues first:
You're invoking the subs function before you're actually defining it.
Your indent of main() is off.
subs is an inner function of main. While not technically incorrect, using inner functions can make your code more difficult to read.
You also have some semantic issues:
subs is only returning true on the escape condition, there is no default return value. This is poor practice
subs is checking if s2 == 0, which it will never be - strings won't equal 0. Empty strings are Falsy, so you can check if the string is empty by using if not s2: instead
Your logic dictates that the recursion will ONLY occur if s2 starts with s1, meaning if s1='ab' and s2='habc', it will not trigger recursion, even though s1 is a substring of s2.
My suggestion would be to reexamine your algorithm. Begin with identifying how you will begin looking for a candidate substring first, then what your escape conditions are, then how you break the problem into a smaller problem.
I rewrote the code you had written, but kept the intuition same. Major problems were:
1.Indentation mistakes at many places.
2.function definition after calling it.
3.Wrong method to find empty string.
def main():
def subs(s1, s2,k):
#If input string is empty .
if k==0 and not s2.strip():
print("Yes")
return 0
#String 1 not empty and search for the sub-string.
elif s1.strip() and s1.startswith(s2):
print("Yes")
return 0
#String 1 not empty and sub-string not matched.
elif s1.strip():
subs(s1[1:],s2,1)
#String empty and sub-string not match.
else :
print("No")
s1 = input("enter string")
s2 = input("enter sub-string")
sub = subs(s1,s2,0)
#print(sub)
main()
I am currently taking a course on Python and am currently struggling with one portion of my homework.
The question is asking us to construct a function that checks a string to see if it is a palindrome. The problem I am having is that for one of the tests my instructor has provided is for the palindrome "Never odd or even" which contains spaces. The spaces are causing my function to fail because it won't just use the letters in the phrase.
My current code is:
def is_palindrome(phrase):
return phrase == phrase[::-1]
She is testing with the code:
assert is_palindrome("Never odd or even")
Any help would be appreciated! Thanks.
I think this is what you want:-
is_palindrome("Never odd or even".replace(" ", "").lower())
Or
If you want to change your function then your function look like:
def is_palindrome(phrase):
phrase=phrase.replace(" ","").lower()
return phrase == phrase[::-1]
and you can call it using is_palindrome("Never odd or even")
First remove the spaces, then use recursion, checking only if the first and last characters are the same, recursing on the inner part.
def is_palindrome(x):
x = "".join(x.split()).lower()
if (len(x) <= 1): return True
if x[0] != x[-1]: return False
return is_palindrome(x[1:-1])
I'm working on a problem which is below and my code. I could use some help.
Write a recursive function check(s) that take a string representing a password as input and returns all the characters that are digits (0 -9)
def check(s):
if not s.idigit():
return
else:
return check(s.isdigit())
def check(s):
if len(s) == 0:
return ''
elif s[0].isdigit():
return s[0] + check(s[1:])
else:
return check(s[1:])
For the example
print(repr(check('12a3z-4!')))
this prints
'1234'
which is what you want. There are other ways to write this code but this is probably simplest for a beginner in Python.
From your last comment, you may want to print out the digits in the password, from largest to smallest, each on a separate line, and you don't care about returning anything from a function. If that's what you want, try
def check(s):
if len(s) > 0:
check(s[1:])
if s[0].isdigit():
print(s[0])
check('31a4z-2!')
This prints
2
4
1
3
Recursion has two main parts:
Base case: what to return when you hit the most trivial input.
Recursion case: how to reduce the problem to something simpler.
Here, your base case is
if s == '':
return ''
Your recursion case depends on whether or not the leading character is a digit. If it is, you want to add it to the string you build; if not, you have nothing to add. Either way, you call your routine on the remainder of the string:
add = ''
if s[0].isdigit():
add = s[0]
After this, call the routine on the rest of the string. When that returns, combine its return value with add, and return that to the calling program.
Does that move you along?
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I need help writing a recursive function which detects whether a string is a palindrome. But i can't use any loops it must be recursive. Can anyone help show me how this is done . Im using Python.
def ispalindrome(word):
if len(word) < 2: return True
if word[0] != word[-1]: return False
return ispalindrome(word[1:-1])
And here is the best one liner
def ispalindrome(word):
return word == word[::-1]
From a general algorithm perspective, the recursive function has 3 cases:
1) 0 items left. Item is a palindrome, by identity.
2) 1 item left. Item is a palindrome, by identity.
3) 2 or more items. Remove first and last item. Compare. If they are the same, call function on what's left of string. If first and last are not the same, item is not a palindrome.
The implementation of the function itself is left as an exercise to the reader :)
If a string is zero or one letters long, it's a palindrome.
If a string has the first and last letters the same, and the remaining letters (I think it's a [1: -1] slice in Python, but my Python is a bit rusty) are a palindrome, it's a palindrome.
Now, write that as a palindrome function that takes a string. It will call itself.
Since we're posting code anyway, and no one-liner has been posted yet, here goes:
def palindrome(s):
return len(s) < 2 or s[0] == s[-1] and palindrome(s[1:-1])
Here's another viewpoint
A palindromic string is
Some letter, x.
Some palindromic substrinng.
The same letter, x, repeated.
Also, note that you may be given a proper English sentence "Able was I ere I saw Elba." with punctuation. Your palindrome checker may have to quietly skip punctuation. Also, you may have to quietly match without considering case. This is slightly more complex.
Some leading punctuation. Some letter, x.
Some palindromic substring.
Some letter, x, repeated without regard to case. Some trailing punctuation.
And, by definition, a zero-length string is a palindrome. Also a single-letter string (after removing punctuation) is a palindrome.
Here's a way you can think of simple recursive functions... flip around the problem and think about it that way. How do you make a palindrome recursively? Here's how I would do it...
def make_palindrome():
maybe:
return ""
elsemaybe:
return some_char()
else:
c = some_char()
return c + make_palindrome() + c
Then you can flip it around to build the test.
The function should expect a string. If there is more then one letter in the string compare the first and the last letter. If 1 or 0 letters, return true. If the two letters are equal call the function then again with the string, without the first and the last letter. If they are not equal return false.
palindrom( word):
IF length of word 1 or 0 THEN
return 0;
IF last and first letter equal THEN
word := remove first and last letter of word;
palindrom( word);
ELSE
return false;
My solution
#To solve this I'm using the stride notation within a slice [::]
def amazonPalindrome(input):
inputB = input
input = input[::-1]
#print input
noPalindrome = inputB + " is not a palindrome"
isPalindrome = inputB + " is a palindrome"
#compare the value of the reversed string to input string
if input[0]!= input[-1]:
print noPalindrome
else:
print isPalindrome
#invoking the def requires at least 1 value or else it fails
#tests include splitting the string,mixing integers, odd amount palindromes.
#call the def
amazonPalindrome('yayay')
a=raw_input("enter the string:")
b=len(a)
c=0
for i in range(b):
if a[i]==a[-(i+1)]:
c=c+1
if c==b:
print a,"is polindrome"
else:
print a,"is not polindrome"
n=raw_input("Enter a number===>")
n=str(n)
l=len(n)
s=""
for i in range(1,l+1):
s=s+n[l-i]
if s==n:
print "Given number is polindrom"
else:
print "Given number is not polindrom"