List entry with sequential search

Asked

Viewed 168 times

1

I am trying to create a variable input function in a list that only allows entering terms not already contained in the list. I’m having trouble finding a logical solution to this, I can’t use break to stop the loop. I’m not taking identation errors, I’m stuck in the loop. Any path suggestions for solving the problem?

    lista = []

    def preencheLista(lista,taml):
        for i in range(taml):
            duplicidade = True
            while duplicidade:
                c=float(input("Entre com o termo\n"))
                lista.append(c)
                for i in range(len(lista)):
                    if c == lista[i]:
                        duplicidade = True 
                    else:
                        duplicidade = False     
        if duplicidade:
            print ("Valor ja existente, digite um novo valor")
        else:
            lista.append(c) 

    print (lista)
#print ("Valor ja existente, digite um novo valor")

if __name__ == '__main__':
    preencheLista(lista, 10)
  • I applied code formatting to your question via button {} editor. Confirm that the code is as it was supposed to be, because the last line does not seem to respect the indentation that is behind

2 answers

1


How about:

def preencheLista( lst, tam ):

    for i in range(tam):

        while True:

            c = float( input("Entre com o termo: ") )

            if c in lst:
                print ("Valor ja existente, digite um novo valor!")
                continue;

            lst.append(c)

            break;

lista = []
preencheLista( lista, 5 )
print(lista);

Testing:

Entre com o termo: 1.5
Entre com o termo: 2.8
Entre com o termo: 3.0
Entre com o termo: 1.44
Entre com o termo: 1.5
Valor ja existente, digite um novo valor!
Entre com o termo: 3
Valor ja existente, digite um novo valor!
Entre com o termo: 0.3
[1.5, 2.8, 3.0, 1.44, 0.3]

0

I did using recursiveness, where runs until the list has 10 values, only I did not handle the repeat message "Value already existing, type a new value", if you want it only put a status in the function signaling when show the message:

lista = []

def preencheLista(lista, contador):
    if contador == 10:
        return

    valor = float(input("Digite um valor: "))

    if valor in lista:
        preencheLista(lista, contador)
    else:
        lista.append(valor)
        preencheLista(lista, contador + 1)

preencheLista(lista, 0)

print(lista)

Browser other questions tagged

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