Can I solve this problem using sort or sorted?

maximum = 0 is technically wrong, if the list contains only negative numbers, isn’t it?

2 Likes

So pick one out of the list, it is. Good catch!

>>> from random import choice
>>> nums = 5, 8, 13, 21, 34, 55
>>> maximum = choice(nums)
>>> maximum
21
>>> 
1 Like

Would this be the fly in the ointment?

This is in the loops section. I didn’t look at the hints (looked after noticing in here that it mentioned using a loop) and nothing in the direct instructions said we had to use a loop, just create a function. This uses only things learned so far.

def max_num(nums):
return sorted(nums)[-1]

Solutions like this sometimes makes me chuckle…or facepalm.

I agree that since it’s an exercise in the “loop” section, it is indeed quite implicit we should use a loop to solve it and not a pre-existing function (the exercise can be solved with two lines of code using “sorted()”.

This is how I solved it:

def max_num(nums):
  maximum = 0
  for i in range(len(nums)):
    if nums[i] > maximum:
      maximum = nums[i]
  return maximum

Any feedback will be greatly appreciated!

Thanks everyone and take care

Excellent point. I didn’t think about changing the order of the list when I used sort() to figure it out. Thank you.

1 Like

Liked your view! Very clever!

Just to add to this discussion:
As part of cataloging different ways of tackling this exercise, I wanted to try and solve it without having to define a variable to keep the max value (and just use indexes), so I wrote this:

#Using for loop, range, list length and indexes.
#Started range from -2 otherwise would not compare the last 2 items.

def max_num(nums):
    for i in range(-2, len(nums)):
        if nums[i] > nums[i+1]:
            return nums[i]
        else:
            return nums[i+1]

Critiques are welcomed. I’m not sure if this is sound logic or if starting the range at -2 and getting the right answer was just sheer luck.

Edit: I tried this code with a list of negative numbers and did not get the right answer, so it probably does not work properly (it is not enough to compare a number with the adjacent one). So my question would now be: is it at all possible to solve this without having to assign the max value to a variable?