The result seems to be right. Just your indentation is wrong. For infinite sequences (collatz is one of them) Generators could be used.
Here is a derivation of your code:
from itertools import count
def ask_int(question):
while True:
user_input = input(question + ": ")
try:
return int(user_input)
except ValueError:
print(f"'{user_input}' is not a valid integer")
def collatz_generator(start):
if start < 1:
raise ValueError("Start must be a positive integer")
n = start
while n > 1:
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
yield n
def collatz_counter(start):
if start < 1:
raise ValueError("Start must be a positive integer")
n = start
for trys in count(1):
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
if n <= 1:
break
return trys
def longest_collatz(start=1, end=100_000):
maximum_length = 0
maximum_value = 0
for value in range(start, end + 1):
length = collatz_counter(value)
if length > maximum_length:
maximum_length = length
maximum_value = value
return maximum_value, maximum_length
if __name__ == "__main__":
print("Find the longest collatz sequence with given start and end")
start = ask_int("Start Value")
end = ask_int("End Value")
value, length = longest_collatz(start, end)
print(f"The start value {value} creates a collatz sequence with {length} values.")
Quote:PS C:\Users\Admin\Desktop> py collatz.py
Find the longest collatz sequence with given start and end
Start Value: 1
End Value: 100_000
The start value 77031 creates a collatz sequence with 350 values.
PS C:\Users\Admin\Desktop> py collatz.py
Find the longest collatz sequence with given start and end
Start Value: 1
End Value: 1_000_000
The start value 837799 creates a collatz sequence with 524 values.
I think the code is also a bit faster.
The generator collatz_generator is not used in the code. I didn't remove it. Maybe you can experiment with it.
gen = collatz_generator(19)
print(list(gen))
In [1]: gen = collatz_generator(19)
...: print(list(gen))
[58, 29, 88, 44, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
The 19 is not included. My mistake. Quick fix just for completeness:
def collatz_generator(start):
if start < 1:
raise ValueError("Start must be a positive integer")
n = start
yield n # <-- this will yield n, which is the start value
while n > 1:
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
yield n # <-- this here are the values after the start value