1

I have a list which contains a word and three different numbers. I want to find a way to select the largest of these three numbers, but whenever I use the max function it selects the word instead. Is there any solution to this?

Part of my code goes as follows:

myList = list()
userName1 = input('What is your name?')
myList.append(userName1)
score1 = input('User 1 score 1')
myList.append(score1)
score2 = input('User 1 score 2')
myList.append(score2)
score3 = input('User 1 score 3')
myList.append(score3)

print(max(myList))

For these, I inputted my name (Daisy) and three numbers (6, 9 and 4). I hoped that the max function would select the 9, but instead it printed Daisy.

6
  • Can you post a working code example? Commented Oct 29, 2015 at 11:59
  • sample input and output to that would be nice Commented Oct 29, 2015 at 12:00
  • 1
    So it is actually a list of all strings, but some of the strings represent numbers. Commented Oct 29, 2015 at 12:05
  • max of list of String gives the longest String in the list hence the Daisy Commented Oct 29, 2015 at 12:10
  • Updated it with an example of my code @Alex Commented Oct 29, 2015 at 12:10

2 Answers 2

2

input() returns a string holding the user's input. You need to convert your strings to integers (the ones that can be), so you could build a new list of these numbers and find the maximum of that one. This is a good use of the try...except clause: just ignore (pass) the exception you get if you try to convert something like 'Daisy' into a number.

In [1]: myList = ['one', 1, 'foo', '4', '5', '2']

In [2]: numbers = []

In [3]: for item in myList:
   ...:     try:
   ...:         numbers.append(int(item))
   ...:     except ValueError:
   ...:         # ignore items which aren't integers
   ...:         pass
   ...:     

In [4]: max(numbers)
Out[4]: 5

At the moment you're comparing string values, which will not give you the necessary maximum even when the string can be converted to integers (e.g. '10' is "less than" '9').

Sign up to request clarification or add additional context in comments.

2 Comments

After the String to Int cast print(max([i for i in myList if isinstance(i,int)])) is much better way
@AnkurAnand But OP's myList, as coded, will contain only strings: i.e. ['Daisy', '6', '9', '4'].
0

Untested suggestion to improve code as a whole:

userName1 = input('What is your name?')
scores = input('User scores, comma seperated')
print("user %s has max score %d"%(userName1, max(map(scores.split(','),int))))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.