How to find the lowest value of a python vector?

Asked

Viewed 964 times

-4

Could someone help me with the logic of this function?

This function must receive an integer vector and return the smallest value within that vector.

Ex: minimo([1,2,3,5,8,9,0,-2]) -> -2

  • Why reinvent the wheel ? min([1,2,3,5,8,9,0,-2]) or more generally min(lista)

  • This exercise was requested on the subject of data structure, so I cannot use the min.

  • 1

    OK so start by studying for and if. With these two you can do what you want.

  • 1

1 answer

3

The logic of its function would be thus:

You create a variable minimo which has the value of the first element of the list (if you do not want to use the same function name, call min or something else).

Then you go through the rest of the list element by element, replacing the value of minimo by the element if it is less than the minimo current.

At the end you return minimo.

For the function to be more resistant to errors you can at the beginning of the function check if the list is empty, and then throw an exception or return a special value.

You may also want to check the type of the parameter lista, After all it may not be a list, or it may not be an everlasting one, or it may not contain integers. These things can cause error at runtime in dynamic languages.

To build this function you need to know the following language elements: for, if, lists, Slices and how to create functions.

Browser other questions tagged

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