Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the max and min from a string in python?

This is my current program. It's outputting the incorrect max and min. What is missing from 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
like image 930
OliverCracker Avatar asked Dec 08 '22 03:12

OliverCracker


2 Answers

When you do string comparisons or try to use min(), max() with strings, you are actually maintaining alphabetical ordering:

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

This is why a lot of the built-in Python functions that rely on positional comparison support the key argument:

>>> 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'
like image 115
Filip Dupanović Avatar answered Feb 13 '23 13:02

Filip Dupanović


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
like image 37
A.J. Uppal Avatar answered Feb 13 '23 14:02

A.J. Uppal