How do I print a table with all iterations in Python?

Asked

Viewed 46 times

1

With the code below I get only the final answers, how do I print each step?


def funcao_volume(x : float):
    return 4*(x**3) - 1014*(x**2) + 62370*x

def calculate_alpha(delta: float):
    numerador = delta*(5**(1/2) -1)
    return numerador/2

def calcuatex1(b : float, alph: float):
    return b - alph

def calcuatex2(a: float, alph: float):
    return a + alph

def abs(a:float, b:float):
    if a>b:
        return a - b
    else:
        return b - a

a = 0
b = 105
resp = list()
erro = 1
it = 1

#Iniciando o processo
while erro > 0.001 or len(resp) < 1000:
    delta = b - a
    alph = calculate_alpha(delta)
    x1 = calcuatex1(b,alph)
    x2 = calcuatex2(a,alph)
    v1 = funcao_volume(x1)
    v2 = funcao_volume(x2)
    if v1<=v2:
        a = x1
    else:
        b = x2
    erro = abs(a,b)
    it = it+1
    resp.append({"it": it, "erro":erro,"v1":v1,"v2":v2,"x1":x1,"x2":x2})

#printando o ultimo resultado
print (resp[-1])


1 answer

0

You can use a loop for to go through all the answers and print them, like this:

for resposta in resp:
    print(resposta)

In this case, you will print each dictionary contained in the list. If you want to get the values of the answers to format what will be printed, use the syntax of the brackets [] passing the key of each value.

In the example below, I will use another for to go through each dictionary key and format the print.

for resposta in resp:

    for chave in resposta:
        print(chave, "=", resposta[chave], end = " | ")

    print("\n")

If you want to make the exit very beautiful with separate values, take a look at this reply another question that talks about Python formatting.

  • Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.