从数学函数自动生成列表?
Automatically generate list from math function?
我的想法是 运行 对任意范围内以 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)
不清楚您具体询问和想知道的内容,因此这只是一个猜测。由于您只想知道序列的长度,因此无需实际保存每个序列中的数字——这意味着只创建了一个列表。
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]
我的想法是 运行 对任意范围内以 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)
不清楚您具体询问和想知道的内容,因此这只是一个猜测。由于您只想知道序列的长度,因此无需实际保存每个序列中的数字——这意味着只创建了一个列表。
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]