Reputation: 37
I am trying to make code that takes a list of numbers starting from a billion to 2 billion with an increment of 100 million and outputs a list of the number of steps it takes to reach one using the Collatz conjecture for each number.
My code:
from math import pow
# Defining the function
def collatz(the_input):
step = 1
while the_input > 1:
if (the_input % 2) == 0:
the_input = the_input / 2
else:
the_input = ((the_input * 3) + 1) / 2
step += 1
return step
the_inputs = []
the_number = pow(10, 9)
increment = pow(10, 8)
while the_number <= 2 * pow(10, 9):
the_inputs.append(the_number)
the_number += increment
print(the_inputs)
Upvotes: 0
Views: 468
Reputation: 338
You can Create a list of all your input like :
inputs = [k for k in range(pow(10,9),2*pow(10,9),pow(10,8))]
And iterate for each element of your list:
outputs = []
for input in inputs :
outputs.append(collatz(input))
print(outputs)
Upvotes: 0
Reputation: 35540
Loop through the list:
for num in the_inputs:
steps = collatz(num)
print(f"it takes {steps} steps for {num}")
This code uses f-strings.
Or, use a list comprehension for a list:
step_list = [collatz(num) for num in the_inputs)]
Upvotes: 1
Reputation: 31354
A version of your collatz
function for lists:
def collatz_list(numbers):
result = []
for number in numbers:
step = 1
while number > 1:
if (number % 2) == 0:
number = number / 2
else:
number = ((number * 3) + 1) / 2
step += 1
result.append(step)
return result
Or you could just reuse your function like this:
result = [collatz(number) for number in the_inputs]
Upvotes: 0