0

I was trying to write a recursive function that returns the collatz sequence of a number, but the code (shown below) doesn't work. How could this be circumvented and why does this happen?

If I write print(x) instead of return x, it can print fine and I can't figure out why it wouldn't be able to return x.

def collatz(x):
    if x[-1] == 1:
        return x
    elif x[-1] % 2 == 0:
        collatz(x + [x[-1]/2])
    elif x[-1] % 2 == 1:
        collatz(x + [3*x[-1] + 1])
1
  • 2
    You return x, but in recursive calls your should also return. Otherwise only innermost call returns x, but the outer ones don't return anything. Basically: collatz(x +... -> return collatz(x +... Commented Aug 21, 2019 at 8:56

2 Answers 2

2

You are missing the returns for the recursive calls. This is what you need:

def collatz(x):
    if x[-1] == 1:
        return x
    elif x[-1] % 2 == 0:
        return collatz(x + [x[-1]/2])
    elif x[-1] % 2 == 1:
        return collatz(x + [3*x[-1] + 1])
Sign up to request clarification or add additional context in comments.

Comments

1

You forgot to return a value from the recursive calls. So each time you call recursively, you're actually returning None.

Add a return before each of the calls to collatz

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.