Python 3 中的递归方法和全局变量问题

2024-10-01 22:39:13 发布

您现在位置:Python中文网/ 问答频道 /正文

代码如下:

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)

我在三个num处得到错误,它们说:unresolved reference 'num',我在运行它时得到错误local variable 'num' referenced before assignment。但是我在方法之前定义了num,那么为什么我会得到这些错误呢?谢谢

编辑:我自己回答的


Tags: the代码inputlenifdef错误length
3条回答

不需要索引或长度

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

但你可能被要求使用它们。。。在

编辑

下面是一个评论,这有效地缩小了可能的反应范围,这里是一个看马,没有切片的版本以上。在

^{pr2}$

print表达式用于显示函数的正在进行的工作,OP可能希望删除它们,因为它们没有被请求(NB:w/oprints等等,它是5个LOC)。在

测试输出

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.

最后的烟火:期待已久的一班

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

在python中,为了跟踪递归过程中需要存在的变量,可以使用带有默认值的参数。在

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')

我将print移到函数之外,并修复了一些错误。在

函数中的变量有一个局部作用域,因此需要在函数中初始化num!但是由于这里有一个递归函数,所以不能在函数中指定num=0。在

所以我对这个问题的建议是:

  • 将num作为参数传递给函数:

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

相关问题 更多 >

    热门问题