Home > Enterprise >  Writing a function to perform Collatz Conjecture
Writing a function to perform Collatz Conjecture

Time:10-06

I am asked to complete the rest of this code:

def collatz_step(n):
    if n % 2 == 0:
        return n // 2 

and write a while loop that will set n to the next value given by collatz_step until it reaches 1, printing the value of n at each step.

which I completed as follows, which should give me 10, 5, 16, 8, 4, 2, 1

def collatz_step(n):
    if n % 2 == 0:
        return n // 2
    else:
        return 3*n   1

while n != 1:
    n = collatz_step(n)
    print(n)

collatz_step(3)

but I get an error saying that 'n' is not defined? this part specifically,

while n != 1:

how do I solve this to get the correct results?

CodePudding user response:

I see two things wrong:

  1. You never define n before trying to use it.
  2. At the end you call the function again but do nothing with the result.

It sounds like you just want to define n and then call the function in your loop, not again at the end. So something like:

# no changes to the function definition

n = 3
while n != 1:
    n = collatz_step(n)
    print(n)

Just think about it semantically... You want to start with a value of 3 and then repeat the operation of updating that value until it equals 1. So first you define a variable with the value you want, then you write a loop in which you update that value until the loop condition is met.

  • Related