簡體   English   中英

如何將列表輸入 function 並在 Python 中接收列表?

[英]How do I input a list into a function and recieve a list in Python?

我正在嘗試編寫代碼,該代碼包含從 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 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

或者您可以像這樣重用您的 function:

result = [collatz(number) for number in the_inputs]

您可以創建所有輸入的列表,例如:

inputs = [k for k in range(pow(10,9),2*pow(10,9),pow(10,8))]

並迭代列表中的每個元素:

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