Python: Generate a geometric progression using lis

2019-07-13 23:12发布

In Python, Can I generate a geometric progression using list comprehensions alone? I don't get how to refer to elements that were added to the list.

That would be like Writing python code to calculate a Geometric progression or Generate list - geometric progression.

2条回答
Lonely孤独者°
2楼-- · 2019-07-13 23:34

If a geometric progression is defined by a_n = a * r ** (n - 1) and a_n = r * a_(n - 1), then you could just do the following:

a = 2
r = 5
length = 10

geometric = [a * r ** (n - 1) for n in range(1, length + 1)]

print(geometric)
# [2, 10, 50, 250, 1250, 6250, 31250, 156250, 781250, 3906250]
查看更多
forever°为你锁心
3楼-- · 2019-07-13 23:59

List comprehensions don't let you refer to previous values. You could get around this by using a more appropriate tool:

from itertools import accumulate
from operator import mul
length = 10
ratio = 2
progression = list(accumulate([ratio]*length, mul))

or by avoiding the use of previous values:

progression = [start * ratio**i for i in range(n)]
查看更多
登录 后发表回答