简体   繁体   English

如何将列表输入 function 并在 Python 中接收列表?

[英]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)

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 .此代码使用f-strings

Or, use a list comprehension for a list:或者,对列表使用列表推导:

step_list = [collatz(num) for num in 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM