Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Generate a geometric progression using list comprehension

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.

like image 773
Pierre B Avatar asked Jul 07 '16 00:07

Pierre B


2 Answers

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)]
like image 186
user2357112 supports Monica Avatar answered Sep 21 '22 00:09

user2357112 supports Monica


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]
like image 44
Alec Avatar answered Sep 24 '22 00:09

Alec