Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python function return None. Why? [duplicate]

count = []

def problem14(n):
    count.append(n)
    if n == 1:
        return count
    if n % 2 == 0:
        n = n/2
        problem14(n)
    else:
        n = 3*n + 1
        problem14(n)


print problem14(13)

So this is code that I have written. I have no idea why it's returning None while in my opinion it should return list 'count'. Any help?

like image 620
Irmantas Želionis Avatar asked Dec 05 '25 20:12

Irmantas Želionis


2 Answers

You still need a return statement when using recursion, otherwise the return value will be lost:

def problem14(n):
    count.append(n)
    if n == 1:
        return count
    if n % 2 == 0:
        n = n/2
        return problem14(n)  # <--
    else:
        n = 3*n + 1
        return problem14(n)  # <--

By the way, this is probably the wrong approach for Project Euler #14 :-) Consider using a dynamic programming approach instead (that's all I'll say so as to not ruin the fun).

like image 170
arshajii Avatar answered Dec 08 '25 09:12

arshajii


You should use the return keyword in order to return a value from a function.

return problem14(n)
like image 41
Yossi Avatar answered Dec 08 '25 08:12

Yossi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!