Problem with a search algorithm on a vector and does not find

Asked

Viewed 79 times

1

The algorithm I am developing should look for an element in any vector. The error happens when the element is not found.

vetor = []

for i in range(1, 5):
    vnum = int(input('Digite um valor: '))
    vetor.append(vnum)
num = int(input("Digite o valor a ser pesquisado: "))

i = 0
achei = False

while i <= 4 and achei == False:
    if num == vetor[i]:
      achei = True
    else:
        i = i + 1
if achei == True:
    print(f'O numero {num} esta na posição {vetor[i]}')
else:
    print(f'O numero {num} não se encontra na lista.')
  • And what’s the mistake?

  • When a value is entered that is not in the list it shows this error: if num == vector[i]: Indexerror: list index out of range

  • 2

    In doing i in range(1, 5) you say i will vary from 1 to 4, because 5 is not inclusive, which results in a list of 4 positions, from 0 to 3. In your loop, you are accessing the positions from 0 to 4, that is, position 4 will never exist in the list.

4 answers

3

The current answers are correct and probably I would do anyway, even for being faster, but I decided to answer because in exercise it may be that the person has to do the algorithm and not use something ready, which is useful for general learning and can show other elements of the language that few know as the else of while. And I also fix a problem that was in the code and generates error (the range() should start at 0). I didn’t try to fix the mistake that if the person doesn’t type a number the application will break, it should be treated in a valid code, and of course, I simplified some things, but I could have used a for in place of while, preferred to leave as AP did. I changed the formation because ideone does not accept f string. The code was more complex than it should have been, but I found no mistake some beyond the stated, gives the correct result in both cases. Therefore, although the answers are correct, it does not solve the real problem that the PA had, although an answer was accepted.

vetor = []
for i in range(0, 5): vetor.append(int(input('Digite um valor: ')))
num = int(input("Digite o valor a ser pesquisado: "))
i = 0
while i < 5:
    if num == vetor[i]: 
        print("O numero {0} esta na posição {1}".format(num, i + 1))
        break
    i += 1
else:
    print("O numero {0} não se encontra na lista".format(num))

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

2

Apart from Maniero’s answer, none returns the index where the element was found in the vector as the author of the question expects, so I’ll leave my collaboration using the method list.index() which returns the index of the found element or raises a ValueError if you don’t find.

lista = [1, 2, 3, 4, 5]
num = int(input("Digite o valor a ser pesquisado: "))

try:
    i = lista.index(num)
    print(f'O numero {num} esta na posição {i}')
except ValueError:
    print(f'O numero {num} não se encontra na lista.')

Repl.it with the code working

2


Python is much cooler, you’re programming in C, buddy!

If you want to verify the existence or not of an element in a list, use the following comparator:

if num in vetor:
    print("Encontrei!")
else:
    print("Nao encontrei!")

About the error you are having, when you do not find i. You add 4 elements in your vector, vector[4] is not defined, but vector[0] up to vector[3]. Your while is accessing vector[4]!

If you want to keep your code, which I don’t recommend, because you’re inventing the wheel

while i <= 3 and achei == False:
  • 1

    Thank you. I already knew the Python method to do, but I wanted to do it in the "hand" to know the logic that exists

1

lista = [1, 2, 3, 4, 5]
num_procurado = 4

if num_procurado in lista:
    print("Contém")
else:
    print("Não contém")
  • Hi Johnatan, could you explain what your answer does?

  • I think Johnatan has simplified as much as possible to say that there is an easier way to look for some element within any vector. My method is much more complex and not recommended in Python, because it violates the zen of python in some aspects, but as I said above: I used the most complex way to understand the logic of some simple search engines using a sequential method.

  • Yes, exactly what @Fabriciopaiva said, Python there are magic methods (simple), which deal explicitly with an easy way to solve a certain recurring problem, bringing more productivity and clarity of code. Explaining the code, I declared a variable of the type list, and I passed it as a condition within the repeat structure in the "if" in simple reading would be "If the searched number contains in the list."

Browser other questions tagged

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