How could I reduce this code?

Asked

Viewed 41 times

-4

def hello_quantum(string):
    """
    hello_quantum: cad. caracteres --> lógico
    funcao permite jogar o jogo praticamente, permite o uso das portas para manipular o tabuleiro
    com o objetivo de igualar o tabuleiro inicial ao tabuleiro introduzido

    """
    a = eval(string.replace(":",",")) # transforma o string num tuplo, onde primeiro elemento eh o tabuleiro,
                                                                    #  e segundo eh o numero jogadas maximas
    num_jogadas = a[1]
    t_objetivo = str_para_tabuleiro(str(a[0]))
    counter = 0
    t_inicial = tabuleiro_inicial()
    tabu = []

    print("Bem-vindo ao Hello Quantum!\nO seu objetivo e chegar ao tabuleiro:")
    print(tabuleiro_para_str(t_objetivo))
    print("Comecando com o tabuleiro que se segue:")
    print(tabuleiro_para_str(t_inicial))


    while num_jogadas > counter and not (t_objetivo == tabu):
        in_porta = input("Escolha uma porta para aplicar (X, Z ou H): ")

        in_lado = input("Escolha um qubit para analisar (E ou D): ")

        if in_porta == "X":
            if in_lado == "E":
                tabu = porta_x(t_inicial,"E")
            else:
                tabu = porta_x(t_inicial,"D")
            print(tabuleiro_para_str(tabu))

        elif in_porta == "Z":
            if in_lado == "E":
                tabu = porta_z(t_inicial,"E")
            else:
                tabu = porta_z(t_inicial,"D")
            print(tabuleiro_para_str((tabu)))

        elif in_porta == "H":
            if in_lado == "E":
                tabu = porta_h(t_inicial,"E")
            else:
                tabu = porta_h(t_inicial,"D")
            print(tabuleiro_para_str(tabu))

        counter += 1

    if tabuleiros_iguais(tabu,t_objetivo):
        print("Parabens, conseguiu converter o tabuleiro em %s jogadas!"%(counter))
        return True

    else:
        return False

Function made with data abstraction, so calls several other functions.

1 answer

1

@user133264, your question is vague, when you ask how to reduce the code. Because reducing can mean doing in fewer lines, reducing processing time, reducing number of loops (which ends up relating to the last two points), etc.

But I’m assuming reducing how to make a more streamlined code.

First point is that you don’t detail the other functions being called, but something that would already reduce the amount of code absurdly, would be:
1. adding a dictionary to map the relationship between in_portas and functions
2. check whether in_lado and in_portas received a valid value
3. exchange all the if, elif and else by a single line of code:

portas = {
            'X': porta_x, 
            'H': porta_h,
            'Z': porta_z
        }
lados = ["E", "D"]

if in_porta not in portas or in_lado not in lados:
     continue

tabu = portas[in_porta](t_inicial,in_lado)

I believe that here you already have a great gain from the inefficiency of loops that you had created. As for the rest of the code, I would need more details of the functions to make it even more efficient, but it seems to me that you were looking for something to optimize the loops even (if not, let me know)

Browser other questions tagged

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