![](/img/trans.png)
[英]Using python to sum n terms of a sequence using only for and while loops
[英]print the sequence of size n in which every term is sum of previous three terms?
arr = [0 for i in range(9)]
arr[0] = 1
for i in range(1,9):
j = i-1
count = 0
sum = 0
while (j>=0 and count < 3):
sum = sum + arr[j]
j = j - 1
count = count + 1
arr[i] = sum
for i in range(0,9):
print(arr[i])
1 1 2 4 7 13 24 44 81
1 1 1 3 5 9 17 31 57
您可以使用动态编程:
def seq(n):
r=[1,1,1]
for i in range(3, n):
r.append(r[i-1] + r[i-2] +r[i-3])
print(' '.join(map(str,r)))
您可以使用用于计算斐波那契数列的代码的修改版本来获得这一点。 这是使用递归:
import functools
@functools.lru_cache()
def sequence3(n):
if n <= 0:
raise ValueError(str(n) + " must be strictly positive")
return 1 if n <= 2 else 2 if n == 3 else sum([sequence3(n-i) for i in range(1,4)])
number_of_elements = 10
print([sequence3[x] for x in range(1, number_of_elements+1)])
您不需要保留整个序列。 最后 3 个元素就足够了。 因为数字很快就会变大(进入 GNU MP 领域),我们还可以通过指定我们不希望发生任何不必要的计算来扩展任务,即,必须同时打印任何计算的内容。
def sequence(n):
data = [1, 1, 1]
for i in range(min(3, n)):
yield data[i]
for i in range(3, n):
s = sum(data)
yield s
data[i % 3] = s
def print_sequence(n):
for s in sequence(n):
print(s)
print_sequence(100)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.