Reputation: 11
I am new at coding and i am trying to do a collatz conjecture.
I think i already made it by i cant code a way to count how much "steps" it takes to the 1.
This is the code i already did.
n = int(input("Enter a number!"))
def lothar(n):
print(n)
if n == 1:
return i
if n % 2 == 0:
n = n / 2
else:
n = ((n*3) + 1)
return lothar(n)
print(lothar(n))
I want to count using a while structure.
For example: in number 4 , it takes 3 steps.
4
2
1.
Upvotes: 0
Views: 302
Reputation: 2032
There's a few ways to count the steps, but I've gone with removing the recursion and using a loop instead:
n = int(input("Enter a number: "))
def lothar(n):
steps = [n]
while n > 1:
if n % 2 == 0:
n = n // 2
else:
n = ((n*3) + 1)
steps.append(n)
return steps
sequence = lothar(n)
print(sequence)
print(str(len(sequence)-1) + " step(s)")
That will return the sequence, which then means we can display the sequence and also output the amount of steps (i.e. the length of the sequence minus one).
For example:
Enter a number: 9
[9, 28, 14, 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
19 step(s)
Upvotes: 1
Reputation: 110
Put the while loop
into the function, and give a count
variable for counting.
n = int(input("Enter a number!"))
count = 1
def lothar(n,count):
while n != 1:
if n % 2 == 0:
count += 1
n = n / 2
else:
count += 1
n = ((n*3) + 1)
return count
print(lothar(n,count))
Because the result you want is to include 4, count will be added one more time, but if you want to count the number of loops
, you should set count to 0 for calculation.
Upvotes: 0