我在python中做了一个简单的collatz函数,它应该返回从值“number”变为1所需的步数。但是,当我发送值为10时,我得到“None”。如果我发送值1和0,我会返回一个整数,但将它们与“>”进行比较返回错误。
这是函数
def collatz_len(number, index=0):
""" returns the collatz len of a number
"""
if float(number) == 1.0:
return index + 1
elif float(number) == 0.0:
return 1
elif float(number) % 2 == 0.0:
collatz_len((number/2), index + 1)
elif float(number) % 2 == 1.0:
collatz_len((3*number) +1, index + 1)
这是我称之为的地方
import collatz
def main():
greatest = 0.0
print("10 >> ", collatz.collatz_len(10))
print("1 >> ", collatz.collatz_len(1))
print("0 >> ", collatz.collatz_len(0))
for i in range(1000000):
if collatz.collatz_len(i) > collatz.collatz_len(greatest):
greatest = i
print(greatest)
这是终端返回的内容
Fresh:3lab fresh$ python3 longest_collatz.py
call collatz_len(number)
10 >> None
1 >> 1
0 >> 1
Traceback (most recent call last):
File "longest_collatz.py", line 14, in <module>
if __name__ == main():
File "longest_collatz.py", line 9, in main
if collatz.collatz_len(i) > collatz.collatz_len(greatest):
TypeError: '>' not supported between instances of 'NoneType' and 'int'