How to create a function to find the highest value in a list?

Asked

Viewed 6,021 times

-4

I’m not getting this algorithm into a function

max_trip = 0

for val in trip_duration_list:
    if int(val) > max_trip:
        max_trip = int(val)
  • And how do you have to enter the function? You need to give criteria, what is parameterized, what returns.

4 answers

4

def maior_valor(lista):
    try:
        if len(lista) == 0:
            return None

        maior = lista[0]

        for valor in lista:
            if valor > maior:
                maior = valor

        return maior
    except TypeError:
        return lista

Considerations:

  1. Due to the dynamic typing of Python, there is no guarantee that the parameter received by the function is of the expected type. The structure try/catch is used to control the program flow if the input is not iterable. When it is, iterate the object by checking its highest value; when it is not, it returns the element itself;

  2. If the input parameter has size 0, it will be returned None, because there are no values to be compared;

  3. The initial value of maior will always be the first element of the list, as this circumvents the problem of starting at 0 but the entry list has only negative elements. The highest value in [-1, -2, -3] can’t be 0.

Limitations:

  1. By comparing value to value, the list is not allowed to have values of different types, such as [1, '2', (3,)]. This makes sense, because a way of comparing different types is not natively foreseen. If considering the fact that, generally, but not necessarily, lists are homogeneous, this is no longer a limitation, but for tuples, which are usually heterogeneous, the problem would continue.

  2. The behavior of the function can be strange when the input is a string, for it will be eternal and the last character will be returned in alphabetical order. That is, maior_valor('anderson') would return 's';

Utilizing:

assert maior_valor([1, 2, 3, 4]) == 4
assert maior_valor([-1, -2, -3]) == -1
assert maior_valor('anderson') == 's'
assert maior_valor(5) == 5
assert maior_valor([]) is None
assert maior_valor('') is None
assert maior_valor([1, '2', (3,)]) == [1, '2', (3,)]

Additional readings:

1

You can use your own max() to do this. Example:

list_1, list_2 = [123, 'xyz', 'Rafinha', 'abc'], [325, 600, 199]
print "Max value: ", max(list_1)
print "Max value: ", max(list_2)

#Max value:  Rafinha
#Max value:  600

If it is a necessity to create a method for this you just need to include this logic in a method.

1

One of the interesting ways to solve this issue is to use an anonymous function (lambda). In this case, the logic should be set up as follows::

  1. Import the library functools along with your method reduce;
  2. Create a variable to store values from your list;
  3. Create a variable to store the highest value obtained from the list;
  4. Display the result.

With this logic we can implement the following code:

from functools import reduce

numeros = [6, 5, 7, 4, 3, 2, 9]
maior = reduce((lambda i, j: i if (i > j) else j), numeros)

print(maior)

When we execute this code the method reduce applies the two-argument function - function lambda - cumulatively to the items of the eternal - numbers - from left to right in order to reduce the eternal value to a single value. In this case, the only value will be the greater list value.

Therefore, when executing this code we receive as a result the value...

9

...which is therefore the highest value obtained from the list.

0

First you need to create a function and say it takes a list as a parameter:

def verificaMaior(trip_duration_list):

then you need to set an initial value to the variable you want to compare:

max_trip = trip_duration_list[0]

right after these two basic points you need to scroll through your list to see if there are any numbers larger than your comparison variable:

for val in trip_duration_list:
    if max_trip < val:
        max_trip = int(val)

Once this is done, just return your variable with updated value (the updated value will only be set if there is a larger number in your list):

return max_trip

Complete code:

def verificaMaior(trip_duration_list):
  max_trip = trip_duration_list[0];
  for val in trip_duration_list:
    if max_trip < val :
      max_trip = int(val)
  return max_trip

print(verificaMaior([1, 2, 3, 4, 10]))

The final print is to show on the console the return of its function.

  • 1

    And if the list is [-1, -2, -3], which is the biggest?

  • in which case it would return max_trip itself right? the code would work right if I made max_trip = trip_duration_list[0] correct? sorry I’m still learning and I try to help with the little I know rsrs

  • Exactly, I mentioned it in this answer.

  • Thanks for the feeedback :)

Browser other questions tagged

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