【问题标题】:Automatically generate list from math function?从数学函数自动生成列表?
【发布时间】:2017-10-24 15:49:49
【问题描述】:

我的想法是在任意范围内对以 1、3、7 和 9 结尾的数字运行 3n + 1 进程 (Collatz conjecture),并告诉代码将每个动作的长度发送到列表,所以我可以单独运行该列表上的函数。

到目前为止,我将单位数字 1,3,7 和 9 指定为:if n % 10 == 1; if n % 10 == 3 ...等等,我认为我的计划需要某种形式的嵌套 for 循环;我在添加列表的地方是拥有temp = []leng = [] 并找到一种方法让代码在每次输入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)

【问题讨论】:

  • 你的问题到底是什么?

标签: python list python-3.6 collatz


【解决方案1】:

目前还不清楚您具体要问什么以及想知道什么,所以这只是一个猜测。由于您只想知道序列的长度,因此无需实际保存每个序列中的数字——这意味着只创建了一个列表。

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]

【讨论】:

  • 这正是我要找的,我不知道这种代码在工作时是什么样子的,我在其他任何地方都找不到。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-07
  • 1970-01-01
  • 2015-12-27
  • 2015-12-20
  • 2014-03-01
  • 2015-07-24
  • 2019-09-25
相关资源
最近更新 更多