Python: Generate a geometric progression using list comprehension

你离开我真会死。 提交于 2020-01-03 15:35:42

问题


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.


回答1:


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)]



回答2:


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]


来源:https://stackoverflow.com/questions/38235829/python-generate-a-geometric-progression-using-list-comprehension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!