2
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?

Irmantas Želionis
  • 2,194
  • 3
  • 17
  • 30

2 Answers2

9

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).

arshajii
  • 127,459
  • 24
  • 238
  • 287
1

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

return problem14(n)
Yossi
  • 11,778
  • 2
  • 53
  • 66