Geometric Progression in python [closed]

-3

Help me make a geometric progression in python that reads an initial value and a ratio and prints a sequence with 10 values.

    
asked by anonymous 14.06.2018 / 21:52

2 answers

3

Assuming a geometric progression is something like:

In% with_of% 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 )

Output:

[2, 10, 50, 250, 1250, 6250, 31250, 156250, 781250, 3906250]
    
15.06.2018 / 03:17
0

Well, no.

The first step is to get input from the user. For this, we use the input function.

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 to their respective number. This is something like this:

{'0': 0, '1': 1, '2': 2...}

Unfortunately, this is terribly annoying to type. The string module will help us with all possible digits:

import string

string.digits  # '0123456789'

Now we have to create a dictionary and assign the key-value pairs to each digit character with its equivalent numeric value. We define a enumerar generator 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 to an integer 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 any operator so that we can use it 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!

That means we can finally have what you commanded us. Suppose the desired factor is 7. So just do

for i in range(10):
    print(Inteiro(7) @ (total ** i))

Result:

2
464
107648
24974336
5794045952
1344218660864
311858729320448
72351225202343936
16785484246943793152
3894232345290960011264
    
15.06.2018 / 03:57