问题描述
我正在尝试编写代码,该代码采用从 10 亿到 20 亿的数字列表,增量为 1 亿,并使用 Collatz 猜想为每个数字输出达到一个数字所需的步骤数列表。
我的代码:
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)
解决方法
遍历列表:
for num in the_inputs:
steps = collatz(num)
print(f"it takes {steps} steps for {num}")
此代码使用 f-strings。
或者,对列表使用列表推导式:
step_list = [collatz(num) for num in the_inputs)]
,
用于列表的 collatz
函数的一个版本:
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
或者你可以像这样重用你的函数:
result = [collatz(number) for number in the_inputs]
,
您可以创建一个包含所有输入的列表,例如:
inputs = [k for k in range(pow(10,9),2*pow(10,pow(10,8))]
并迭代列表中的每个元素:
outputs = []
for input in inputs :
outputs.append(collatz(input))
print(outputs)