How to find max and min from string in python?

This is my current program. It displays the wrong max and min. What is missing in my if statement?

def palin():
  max = 0
  min = 50
  numbers = "23","3","4","6","10"
  for x in numbers:

    if x>max:
      max=x
    if x<min:
      min=x

  print max
  print min
+4
source share
4 answers

When you do string comparisons or try to use min(), max()with strings, you actually maintain the alphabetical order:

>>> sorted(numbers)
['10', '23', '3', '4', '6']

This is why many of Python 's built-in functions that rely on support for positional comparison : key

>>> numbers
('23', '3', '4', '6', '10')
>>> sorted(numbers, key=int)
['3', '4', '6', '10', '23']
>>> min(numbers, key=int)
'3'
>>> max(numbers, key=int)
'23'
+8
source

Your numbers are strings. First convert them to integers:

numbers = [int(num) for num in numbers]

def palin():
  max = 0
  min = 50
  numbers = "23","3","4","6","10"
  numbers = [int(num) for num in numbers]
  for x in numbers:

    if x>max:
      max=x
    if x<min:
      min=x

  print max
  print min
+2
source

python built-in /.

max() min() .

str_numbers = ("23", "3", "4", "6", "10")
numbers = [int(n) for n in str_numbers ]  # convert to integers
max_value = max(numbers)
min_value = min(numbers)

max() min() , :

str_numbers = ("23", "3", "4", "6", "10")
max_value = max(int(n) for n in str_numbers)
min_value = min(int(n) for n in str_numbers)
+1
source

If you installed Numpy, you can easily get the result.

import numpy as np

numbers = ["23","3","4","6","10"]
numbers = [int(n) for n in numbers]
numpy_array = np.array(numbers)
print 'Max:  ', numpy_array.max()
print 'Min:  ', numpy_array.min()
print 'Mean: ', numpy_array.mean()
+1
source

Source: https://habr.com/ru/post/1583906/


All Articles