道格拉斯·霍夫施塔特的普利策奖著作“哥德尔、埃舍尔、巴赫”提出了以下数学难题:
数字n将上下移动,但最终以1结尾(至少对于所有尝试过的数字--没有人能证明序列会终止)。类似地,冰雹在大气层中上下移动,最终降落在地球上。N的值序列通常被称为Hailstone序列,因为冰雹在降落到地球之前也会在大气中上下移动。
使用递归实现有意义吗?我在下面写了一些不好的解决方案。请纠正我。
def hailstone(n):
if(n<0):
print("Invalid input")
return
if(n==1):
print(1)
return
if(n%2 == 0):
print(n)
hailstone(n/2)
return
if(n%2==1):
print(n)
hailstone((n*3) + 1)
return如何将n<0条件移到正确的位置?
发布于 2014-07-08 07:36:05
您的代码有点笨拙,主要原因是:
if(n<0):应该是if n < 0: )。几点意见:
def hailstone(n):
if(n<0):
print("Invalid input") # should be an exception
return # don't need explicit return[ None]
# what if n == 0?
if(n==1):
print(1) # same as print(n)
return # see above
if(n%2 == 0): # n == 0 comes here and loops indefinitely
print(n) # repeat
hailstone(n/2)
return # repeat
if(n%2==1): # should just be else
print(n) # repeat
hailstone((n*3) + 1)
return # repeat将所有print(n)移到顶部,将所有return (隐式)移动到底部的另一种选择是:
def hailstone(n):
"""Print the terms of the 'hailstone sequence' from n to 1."""
assert n > 0
print(n)
if n % 2 == 0:
hailstone(n / 2)
elif n > 1:
hailstone((n * 3) + 1)https://codereview.stackexchange.com/questions/56288
复制相似问题