I'm doing a simple collatz function in python, which should return the number of steps it takes to go from value "number" to 1. However, when I send a value of 10, I get "None". If I send the values 1 and 0, I get an integer returned, but comparing them with ">" returns an error.
Here's the function
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)
Here's where I'm calling it
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)
Here's what the terminal returns
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'