0

Here is the code:

aWord = input("enter the word now")
num = 0

def palindromeMethod(theWord):
    length = len(theWord)
    if(theWord[num]==theWord[length-num]):
        if(num>length):
            print("its a palindrome")
        num = num+1
        palindromeMethod(theWord)
    else:
        return False

palindromeMethod(aWord)

I am getting errors at the three nums, which say: unresolved reference 'num', and I am getting the error local variable 'num' referenced before assignment when I run it. But I defined num before the method, so why am I getting these errors? thanks

edit: answered it myself

6
  • why do you have parens around your if statements? Commented Nov 13, 2014 at 23:46
  • Besides the n problem, you have at least 2 other problems (1) you keep computing the length of the word, at every invocation of the function... it remains the same (2) you start comparing the first and the last character and go on up to compare the last character with the first... isn't there a bit of repetition? Commented Nov 14, 2014 at 0:05
  • @gboffi the point of this exercise is to do it without slicing Commented Nov 14, 2014 at 2:07
  • My points above are nonetheless as true now as they were true before your a little late, but still welcome clarification. Commented Nov 14, 2014 at 8:18
  • @PadraicCunningham «why do you have parens around your if statements?» and why you have camelCaseVariables? and why you cannot use slices? my guess is that the OP is introduced to Java using Python as an easy to use, not over-syntaxed(?) learning tool... Commented Nov 15, 2014 at 7:41

4 Answers 4

2

In python, to keep track of variables that need to exist during the recursion, you use an argument with a default value.

def palindromeMethod(theWord, num=0):
                       # here ^
    length = len(theWord)
    if(theWord[num]==theWord[length-num-1]):
        if(num>=length-1):
            return True
        return palindromeMethod(theWord, num+1)
                          # pass it here ^
    else:
        return False

if palindromeMethod('aabbccbbaa'):
   # don't need to pass it here ^
    print('its a palindrome')

I moved the print outside the function and fixed some off-by-one errors.

Sign up to request clarification or add additional context in comments.

1 Comment

I spent the last 30' praising your answer to the OP, what else can I do? imho there are still a couple of points to be polished but it's good that you stayed very close to the OP approach
2

Variables inside the functions has a local scope ,thus you need to initial the num inside the function ! But as you have a recursion function here you couldn't specify a num=0 in your function .

So my suggestion for such problem is :

  • pass the num as an argument to your function :

def palindromeMethod(theWord,num=0):
   length = len(theWord)
   if(theWord[num]==theWord[length-num]):
       if(num>length):
            print(theWord, "is a palindrome")
            return True
       num = num+1
       return palindromeMethod(theWord,num)
   else:
       return False

6 Comments

01:25 UTC I think that the variable i, in if i>length:, is just a typo for num. But then you call recursively palindromeMethod with the same state as before! StackOverflow... Who has upvoted your answer?
@gboffi As the OP's question and problem is all about local variable 'num' referenced before assignment i just answer to that ! if he tell about other problems then i attempt to refine those for !
Kasra, (1) if word[0] == word[-1] your code will spiral in infinite recursion, a fact is a fact is a fact (2) let's focus on n: the correct answer is parchment's one, not yours! you set n=0 on every invocation of the function!!! this use case is solved only using a default value because a recursive algorithm needs a change of state before the recursive call (well, instead of using a default value you could force the user to provide explicitly the default value in the 1st call from the user program, but that's kind of silly). I have no more characters in this comment, ciao
@gboffi im agree with you 100 % , problem is this that i miss recursion function ! i need to edit the answer ! thanks for your attention and reminding ! ;)
All is well... but then you haven't read the title of the question: "issue with recursive method...". Ok, don't look at me like that! I'll stop bothering! promised! ;-) Ciao
|
2

No need for indices or lengths

def pal(w):
    if w == "": return True
    if w[0] != w[-1]: return False
    return pal(w[1:-1])

but you may have been requested to use them...

Edit

Following a comment of the OP, that effectively narrows the spectrum of possible responses, here it is a look ma, no slices version of the above.

def pal(w, l=0, n=0):

    # in production use: l = l if l else len(w)
    if l ==0:
        l = len(w)
        print(("0123456789"*3)[:l])
        print(w)

    print(n, l-n-1, w[n], w[l-n-1])
    if w[n] != w[l-n-1]: return False
    if n+1 >= l-n-2: return True
    return pal(w,l,n+1)

# a bit of testing
for word in ('aabbcbbaa', 'aabbccbbaa', 'aabbccbaa', 'aabbcdbbaa',
             'saippuakivikauppias'):
    print('Is the word "%s" palindrome? %s.' % (word, pal(word)))

The print expressions were used to show the work in progress of the function, the OP may want to remove them, as they were not requested (NB: w/o prints etc it's 5 LOC).

Output of testing

012345678
aabbcbbaa
0 8 a a
1 7 a a
2 6 b b
3 5 b b
Is the word "aabbcbbaa" palindrome? True.
0123456789
aabbccbbaa
0 9 a a
1 8 a a
2 7 b b
3 6 b b
4 5 c c
Is the word "aabbccbbaa" palindrome? True.
012345678
aabbccbaa
0 8 a a
1 7 a a
2 6 b b
3 5 b c
Is the word "aabbccbaa" palindrome? False.
0123456789
aabbcdbbaa
0 9 a a
1 8 a a
2 7 b b
3 6 b b
4 5 c d
Is the word "aabbcdbbaa" palindrome? False.
0123456789012345678
saippuakivikauppias
0 18 s s
1 17 a a
2 16 i i
3 15 p p
4 14 p p
5 13 u u
6 12 a a
7 11 k k
8 10 i i
Is the word "saippuakivikauppias" palindrome? True.

Final fireworks: the much expected one-liner

def pal(w): return 1 if w=="" else 0 if w[0]!=w[-1] else pal(w[1:-1])

2 Comments

Trust me no one would expect that one liner
@PadraicCunningham "eagerly awaited"? ciao
0

ok I played around with it and came up with this, which works with no errors:

aWord = input("enter the word now")
num = 0

def palindromeMethod(theWord, num):
    length = len(theWord)


    if(theWord[num]==theWord[length-(1+num)]):
        if(num>=length-1):
            print("its a palindrome")
            return True
        num = num+1
        palindromeMethod(theWord,num)
    else:
        return False

palindromeMethod(aWord,0)

however i am not 100% certain why this works. I'm guessing that when i say 'return True' it breaks out of the outer if block and doesn't execute the next two lines in the if block (num = num+1 and palindromeMethod(theWord,num).... is this correct?

4 Comments

Almost there, very well. Improvements? Use a default value for n, as shown in @parchment answer, and possibly use also a default value for length instead of calling len each time you invoke the function (calling len is not a problem, not really, in terms of time elapsed, but it's a bad habit that could bite you if you don't cache the results of heavier functions). Eventually, you're doing a bit too much, comparing 1st to last, 2nd to penultimate, ... penultimate to 2nd and last to 1st. Try a manner to stop in the half! Ciao from
Ah, and add a return before the recursive call, always a return before the recursive call. Again, look at parchment's answer and you'll see the light.
@gboffi thanks so much for all your help so far :) question: why do i need return before the recursive call? it is working fine without it. thanks
It depends on your definition of "it works"... If you think of yourself trying one word at a time and looking at the response on the screen, then "it works" without the last return because when the deepest called function is able to decide it prints 'yes' or 'no' and you see it. Now think of a program to examine a big literary corpus find all the palindromes used, count the uses of each and sort the results... would you like to stay in front of the screen taking notes of which words are recognized and printed, taking track of the count? No. Your main has to examine what the function returns..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.