2
def my_max():    

#using input to collect number to list 
list_a = input("print your list with numbers: ").split(",")  

# Searching for the highest number
      max = 0
      for i in list_a:
           if i > str(max):
      max = i
print(max)

my_max()

When i write numbers to input, sometimes the highest number is being printed, but not always.

For an example, if i write :"54,64,446 " the number "64 is being printed. Do anybody knows why?

2
  • what language is this? Commented Oct 15, 2018 at 18:31
  • oh, sorry! It´s python 3.7 Commented Oct 15, 2018 at 18:33

2 Answers 2

2

You need to map it into list of ints before you do the logic:

def my_max():    

    # using input to collect number to list 
    list_a = input("print your list with numbers: ").split(",")  

    # Searching for the highest number
    return max(map(int, list_a))

print(my_max())

Sample run:

print your list with numbers: 54,64,446
446

Splitting on ',' gives you a list of strings. What you observed is an expected behaviour because you find max of a list of strings in contrast to list of integers.

Without using a max(), I would go something like this:

def my_max():    

    # using input to collect number to list 
    list_a = list(map(int, input("print your list with numbers: ").split(",")))

    # Searching for the highest number
    max = list_a[0]
    for x in list_a[1:]:
        if x > max:
            max = x
    return max

print(my_max())
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! One more question, can I do it without using max()?
@Rapoo Yes, see my answer.
@Rapoo you better use default max() function because in runtime it is way faster.
0

Your list_a contains strings, not numbers. When you do your comparison, you are comparing the values of these strings. The result of this is the highest value alphabetically, rather than numerically.

Taken as strings rather than numbers, 64 > 54 > 446

1 Comment

Thank you, now I see the problem.

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.