从数学函数自动生成列表?

2024-04-26 10:05:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我的想法是对任意范围内以1、3、7和9结尾的数字运行3n+1进程(Collatz conjecture),并告诉代码将每个操作的长度发送到一个列表,这样我就可以分别在该列表上运行函数。你知道吗

到目前为止,我所做的是将单位数字1、3、7和9指定为:if n % 10 == 1if n % 10 == 3…等等,我认为我的计划需要某种形式的嵌套for循环;我所做的列表附加就是在每次输入temp = []leng = []之前找到一种方法让代码自动temp.clear()。我假设有不同的方法可以做到这一点,我愿意接受任何想法。你知道吗

leng = []
temp = []
def col(n):
    while n != 1:
        print(n)
        temp.append(n)
        if n % 2 == 0:
            n = n // 2
        else:
            n = n * 3 + 1
    temp.append(n)
    print(n)

Tags: 方法函数代码列表if进程结尾单位
1条回答
网友
1楼 · 发布于 2024-04-26 10:05:58

不清楚你具体在问什么,想知道什么,所以这只是猜测。因为您只想知道序列的长度,所以不需要实际保存每个序列中的数字,这意味着只创建了一个列表。你知道吗

def collatz(n):
    """ Return length of Collatz sequence beginning with positive integer "n".
    """
    count = 0
    while n != 1:
        n = n // 2 if n % 2 == 0 else n*3 + 1
        count += 1
    return count

def process_range(start, stop):
    """ Return list of results of calling the collatz function to the all the
        numbers in the closed interval [start...stop] that end with a digit
        in the set {1, 3, 7, or 9}.
    """
    return [collatz(n) for n in range(start, stop+1) if n % 10 in {1, 3, 7, 9}]

print(process_range(1, 42))

输出:

[0, 7, 16, 19, 14, 9, 12, 20, 7, 15, 111, 18, 106, 26, 21, 34, 109]

相关问题 更多 >