How to get the lowest value in a list?

Asked

Viewed 10,609 times

3

I’m stuck in this program, I can’t create a function in Python.

The exercise is as follows:

Write a function called buscarMenor() that takes a list of integers and returns the smallest of the elements. Also write the main program that passes the list to the function and displays the return. The search for the smallest element must be performed using a repetition structure, and the use of the min() function is prohibited. Example:

Entry: 7.0 5.5 6.0 9.0 Output: 5.5

What I’ve done so far:

listaInteiros = []
i = 0

while i < 4:
    inteiros = int(input())
    listaInteiros.append(inteiros)
    i += 1
print(listaInteiros)

def buscarMenor():

I’m stuck in the function, give me a boost please!

  • According to the PEP8, function names should use Snake case (although there are several other ways to call it). Since you are learning, try already to follow the conventions. Your function buscarMenor should preferably be called buscar_menor.

2 answers

2


Suggestion:

def buscarMenor(lst):
    i = float("inf")
    for nr in lst:
        if nr < i:
            i = nr
    return i

listaInteiros = [7, 5, 6, 9]
menor = buscarMenor(listaInteiros)
print(menor) # 5

listaDecimais = [7.0, 5.5, 6.0, 9.0]
menor = buscarMenor(listaDecimais)
print(menor) # 5.5

By steps it would be:

  • define the function
  • give the highest possible value in the declaration/assignment of i
  • iterate the numbers of the lists
  • if the iterated number is less than the i, replace the i for this

Then to run just call the function with a list of numbers and save its return in a variable.

  • What is this argument?

  • @Pigot It’s a list/array, I shortened the name... buscarMenor(listaInteiros)

  • Can you clarify the whole program for me? I’m in doubt

  • @Pigot, did you see the end of the answer where I write "by steps"? What part do you understand and what part do you not understand? (so I can be clearer)

  • How do I call two arguments in the main program?

  • @Pigot can pass more arguments to the function separated by commas. And inside the function receive one by one. It makes sense?

  • 1

    Thanks man, you helped me a lot!!

Show 2 more comments

0

def buscarMenor(lista):
    menor = lista[0]
for i in lista:
    if i < menor:
        menor = i
return menor
print(buscarMenor([7.0,5.5,6.0,9.0]))
  • 1

    Why are you replying so often? There is no need for this, it is for this purpose that there is the EDIT button below, so that you correct what needs to be corrected instead of having to create a new post.

Browser other questions tagged

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