Print the minimum number on the list?

Asked

Viewed 153 times

1

I have this code and I can’t get the number -1 to be shown. It gives an error:

not supported between instances of 'str' and 'int'.

From what I’ve seen on other forums it has to do with comparing strings with integers. How can I overcome this?

list1=[2,2, 'a', 31, int(-1), 'b']
list2=[1, 3, 40]
list1[len(list1):]=list2
list1.append(5)

print (len(list1))
print (sorted (list1[7:]))
print (min(list1))

print (list1)

2 answers

3


I think the best way is to ignore what not a number.

This is because if the smaller number has floating point the other proposed solution will ignore it.

In Python3 this is very easy

import numbers
min([x for x in list1 if isinstance(x, numbers.Number)])

Take this test

list1=[2, 2, 'a', 31, int(-1), 'b']
list2=[1, 3, 40]
list1[len(list1):] = list2
list1.append(5)
list1.append(-3.0)

min([x for x in list1 if isinstance(x, numbers.Number)])
# Saída: -3.0

min(filter(lambda x: isinstance(x, int), list1))
# Saída: -1
  • An alternative is to do: min([x for x in list1 if type(x) in (int, float)])

2

Use filter to remove the non-integer values from your list:

list1 = [1, 2, 3, 'b']

result = min(filter(lambda x: isinstance(x, int), list1))

print(result)

The function filter return all items from the list through the callback past, if the sentence is true.

That is to say:

lambda x: isinstance(x, int)
  • I have not learned this function (filter) there is no other way?

  • @Miguel but filter does not change the original list. That is why I did not do this.

  • 1

    @And if the smallest number was -2.0?

Browser other questions tagged

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