1

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'
martineau
  • 119,623
  • 25
  • 170
  • 301
  • You need to return the result of the recursive call. `return collatz_len(...)` – Patrick Haugh Dec 03 '17 at 21:59
  • Is there a specific reason to use `float()` when calculating integer values for a Collatz sequence? – Mr. T Dec 03 '17 at 22:27
  • thank you Patrick, that fixed it. And I use Float() because the first few times, it would stay an int if it was a sequence of even numbers, and turn into a float after being divided by 2, so I just wanted to be consistent. – Donovan Jenkins Dec 04 '17 at 00:19
  • I see. You can avoid this float conversion by using `//`, which will return an integer. The problem with float is that Python integer has (theoretically) an unlimited precision for large numbers, while for float you have to specifically use the `Decimal` module. I had some nasty rounding or overflow errors in programs due to automatic integer - float conversion. See for instance here: https://stackoverflow.com/q/18928004/8881141 – Mr. T Dec 04 '17 at 09:41
  • PS: Only the OP gets automatically a notification for new comments, everybody else you have to address specifically with @name, otherwise they don't know that you answered. – Mr. T Dec 04 '17 at 09:46
  • oh snap, thanks @Piinthesky. This is my first stack overflow question. And thank you for the decimal tip, I had no idea! – Donovan Jenkins Dec 04 '17 at 17:27

0 Answers0