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.
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)]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With