1
def sequence(n):
    while n!=1:
        print(n)
        if n%2==0:
            sequence(n/2)
        else:
            sequence(n*3+1)


sequence(53)

This loop is not terminating. I don't understand why.

2
  • 2
    You never change n inside your function so the while loop never terminates. Perhaps you meant if n != 1:? Commented Jun 30, 2020 at 15:51
  • 1
    You don't need both a while loop and recursion. Commented Jun 30, 2020 at 15:51

2 Answers 2

1

Remove the while loop. You don't need that as the recursive function is doing its job.

Here is the corrected version of your code:

def sequence(n):
        print(n)
        
        if n == 1:
            return
        elif n%2==0:
            sequence(n//2)
        else:
            sequence(n*3+1)


sequence(53)

Change the n/2 to n//2 so that it doesn't become a float.

Sign up to request clarification or add additional context in comments.

Comments

0

The sequence will end at 2, 2, 2, 2, 2... because no matter what n equals at first, it will go down to 2, and then:

n = 2

2 / 2 = 1     # sequence(1)
1 * 3 + 1 = 4 # sequence(4)
4 / 2 = 2     # sequence(2)
2 / 2 = 1     # sequence(1)
1 * 3 + 1 = 4 # sequence(4)
4 / 2 = 2     # sequence(2)
...           # ....

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.