Python函数不返回Bool valu

2024-05-15 09:47:40 发布

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

Possible Duplicate:
Why does 'return self' return None?

我一直在试图解决Euler项目的第55题(http://projecteuler.net/problem=55) 现在我想我有了答案,我遇到了一个问题。我不想在我做错什么的基础上解决问题55。在

这是我的准则:(我认为你不需要全部)

t=0
lychrel=0
called=0

def iteratepal(n):
    global t
    global called
    called+=1
    b = int(''.join(reversed(str(n))))
    #print ("n =",n,"\nb =",b,"\nb+n =",b+n,"\n")

    if ispal(b+n) or ispal(n):
        t=0
        return False

    if t<50:
        t+=1
        iteratepal(b+n)
    else:                          # Here's the prob
        t=0                        # this block is executed (because it prints "yea")
        print("yea")               # but it doesn't return True!
        return True                # you can try it yourself (even in the interpreter)

def ispal(n):
    if n == int(''.join(reversed(str(n)))):
        return True
    return False

print(iteratepal(196))

for i in range(0,200):
    if iteratepal(i)==True:
        lychrel+=1
        print(i,"is Lychrel!")
    else:
        print(i,"is not a Lychrel!")
print(lychrel)

谢谢你的帮助,我真的很困惑。在


Tags: truereturnifisdefitglobalint
2条回答

t < 50时递归调用函数,但不要对返回值执行任何操作:

if t<50:
    t+=1
    iteratepal(b+n)
else:                          
    t=0                        
    print("yea")               
    return True

那么else:分支永远不会执行,因此返回None。您可能希望返回递归调用的结果:

^{pr2}$

一些进一步的提示:

  • 不需要测试==Trueif语句中,以下操作就可以了:

    if iteratepal(i):
    
  • 您可以返回def ispal(n)中的测试本身是一个布尔结果,只需返回不需要测试的结果:

    def ispal(n):
        return n == int(''.join(reversed(str(n))))
    

你没有返回递归的结果。改变这个

if t<50:
    t+=1
    iteratepal(b+n)

为了这个

^{pr2}$

相关问题 更多 >