-3
Help me make a geometric progression in python that reads an initial value and a ratio and prints a sequence with 10 values.
-3
Help me make a geometric progression in python that reads an initial value and a ratio and prints a sequence with 10 values.
3
Assuming that a geometric progression be something like:
In Python
this could be calculated as follows:
a = 2
r = 5
tam = 10
pg = [ a * r ** (n - 1) for n in range(1, tam + 1) ]
print( pg )
Exit:
[2, 10, 50, 250, 1250, 6250, 31250, 156250, 781250, 3906250]
0
That’s right.
The first step is to get input from the user. For this, we use the function input
.
entrada_str = input('n: ') # '232'
Unfortunately, this gives us a string, which is useless for our calculations.
To convert the string to an integer, we can make a dictionary (key-value pair) of each character of the string for its respective number. I mean, something like that:
{'0': 0, '1': 1, '2': 2...}
Unfortunately, this is terribly boring to type. The module string
will help us bringing all possible digits:
import string
string.digits # '0123456789'
Now we have to create a dictionary and assign to the key value pairs each digit character with its equivalent numerical value. We define a generator enumerar
to help us count the numbers:
def enumerar(iterador):
contador = 0
for elemento in iterador:
yield contador, elemento
contador += 1
dicionario_digitos = {}
for i, digito in enumerar(string.digits):
dicionario_digitos[digito] = i
print(dicionario_digitos) # {'0': 0, '1': 1, '2': 2, ...}
Great. We can use our dictionary to convert the original string into an integer number now.
total = 0
for i, caractere in enumerar(entrada_str):
total += dicionario_digitos[caractere] * int('1' + '0' * (len(entrada_str) - i - 1))
print(total) # 232
Now we have to invent multiplication. We create a class Inteiro
and overload some operator so we can use him with a int
and get the result of the multiplication between one and the other. Suppose we use the operator @
.
class Inteiro:
def __init__(self, valor):
self.valor = valor
def __matmul__(self, other):
total = 0
for i in range(other):
total += self.valor
return total
a = Inteiro(2)
print(a @ 3) # 6
Success!
This means we can finally have what you have commanded us. Suppose the desired factor is 7. Then, just do
for i in range(10):
print(Inteiro(7) @ (total ** i))
Upshot:
2
464
107648
24974336
5794045952
1344218660864
311858729320448
72351225202343936
16785484246943793152
3894232345290960011264
Browser other questions tagged python
You are not signed in. Login or sign up in order to post.
You already have some code you’ve tried?
– Victor Stafusa
https://ideone.com/JI9cnf
– user60252