[英]How do I input a list into a function and recieve a list in Python?
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.我正在尝试编写代码,该代码包含从 10 亿到 20 亿的数字列表,增量为 1 亿,并使用每个数字的 Collatz 猜想输出达到一个所需的步骤数列表。
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)
A version of your collatz
function for lists:您的
collatz
z function 版本的列表:
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:或者您可以像这样重用您的 function:
result = [collatz(number) for number in the_inputs]
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.