Can I solve this problem using sort or sorted?

I don’t get why they put this in the loops section because I passed it without doing a loop and my code is way simpler than what a loop would be:

#define max_num
def max_num(nums):
#sort nums list
nums.sort()
#return final variable/ largest number in nums list
return nums[-1]

Maybe I just cheated, but I felt like this answer would make more sense if this was an actual objective in the real world.

1 Like

At the very least, we should be able to take an unsorted list and parse out the minimum and maximum value using a simple algorithm, rather than built-in functions.

>>> from random import randint, shuffle
>>> u, v = randint(1, 1000), randint(1, 1000)
>>> if u > v:
	u, v = v, u

	
>>> y = list(range(u, v))
>>> shuffle(y)

Let’s pretend we don’t know the range that the list is created from and that this block of data was dropped in our lap.

>>> minimum, maximum = y[0], y[-1]
>>> for n in y:
	if n < minimum:
		minimum = n
	elif n > maximum:
		maximum = n

		
>>> minimum, maximum
(421, 921)
>>> 
1 Like

It’s a good observation that you can find min/max at the ends of a sorted list, however, the work carried out is more than is required.

Hi Kell215,

I used almost the same solution as you did it, but using sorted… not sure if these answers are the correct but I believe is better than use a loop…

def max_num(nums):
#Sorting list
l1 = sorted(nums)
return l1[-1]

Would sorting add to the workload, or take away from it?

>>> from random import randrange
>>> def maximize(a, b):
    return a > b and a or b

>>> sample = [randrange(1000000) for _ in range(1000000)]
>>> u = sample[0]
>>> for v in sample:
	u = maximize(u, v)

	
>>> u
999999
>>> 

As we would expect, the highest number may never be generated. In a subsequnet test we got,

>>> sample = [randrange(1000000) for _ in range(1000000)]
>>> u = sample[0]
>>> for v in sample:
	u = maximize(u, v)

	
>>> u
999997
>>> 

this is what i did

def max_num(nums):
nums.sort()
return nums[-1]

is this the best solution?
if not, why.

When working with lists we must consider whether mutability is a possibility, or not. If not, then we cannot sort the list else it will be mutated from the original.

To preserve the original order of the list, while using your method,

return nums.copy().sort()[-1]

The copy will be only temporary, and the original will still be intact.

Sorting is a complex process, more so than iterating once through a list, so on the face of it, your solution would not be ‘the best’ where Big-O is concerned.

a = nums[0]
for x in nums[1:]:
    if x > a: a = x
return a

The sort() process takes up more time than the simple search to find a maximum, at least in the average and worst cases.

Besides, the point of these exercises is to find an algorithm to do the job, not a built in method or function.

My first thought was simply:

def max_num(nums):
nums.sort()
return nums[-1]

It results in the correct answer no matter how many times I change the numbers in the list. Is this acceptable or have I missed something in the question?

I did figure my own way as well without using built in functions like .sort() but for all intents and purposes would my original function be okay outside of the question?

1 Like

It’s not as much as how we can do this task, but how we can do it without resorting to built in methods. It is intended as practice in writing algorithms that get to the core of a task.

def max_num(nums):
    max = nums[0]
    for x in nums:
        if x > max:
            max = x
    return max

Outside of the question, we could just as easily use the max() function and save ourselves writing more code than we need. That’s what those functions are for… To save us time and code. When we understand what and how they work, it makes it easier to appreciate why they are part of the language.

Algorithms are more about expressing ideas than just code. Never discount the value of a good algorithm, no matter how naive it may be. It’s nice to know that if all we have is a screwdriver and thumb wrench we can still do the job.

1 Like

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

this is a shortcut

This exercise was kinda tricky cause it asks you (in the hints) to not use tools you already know.
Like to find the max you could just do:
def max_num(nums):
sorted_nums = nums
sorted_nums.sort()
return sorted_nums[-1]

or whats really easy…

def max_num(nums):
return max(nums)
Using a loop for this goal seems like a huge waste of time/effort. I understand the point of the exercise is to practice using loops… but it just seems weird…

6 Likes

At first, I was thinking the same. Now (with not even so much practice) some mental approaches that seemed odd are now just natural and automatic.

I guess, even with the little time I dedicated to this subject, that the best way to memorize a concept is through practice and that’s the point of this and many other exercices.

Just my opinion of course.

5 Likes

This one was wasy!

You have to use loops, that’s the whole point of this exercise so although this is correct, it’s not a solution to this particular challenge.

This is my solution. Maybe it’s clumsy but it works whether the list is sorted or unsorted.

def max_num(nums):
  maximum = nums[0]
  for num in nums:
    maximum += num
    if maximum == max(nums) and max(nums) > maximum:
      break
  return max(nums)

Do you realize that you do not need anything but the return line?

def max_num(nums):
#  maximum = nums[0]
#  for num in nums:
#    maximum += num
#    if maximum == max(nums) and max(nums) > maximum:
#      break
  return max(nums)

None of the preceding code does anything to help execute the function. In fact, the if condition:

if maximum == max(nums) and max(nums) > maximum:

… can never be satisfied. Look at it: under what values of maximum and nums could it return True?


Please realize: In a beginning coding course, it is very common to be assigned tasks for which there already exists a function. Unless the instructor specifically asks you to do so, simply plugging in that pre-existing function (in this case, max()), although it may get a green check when run through the automated grader, does not satisfy the assignment.

Didn’t your teachers at one time ask you to learn long division and multiplication despite the fact that you had access to a calculator?

2 Likes

I do need it since the assigment is asking me to use a loop to solve the problem. I’ve been here studying for 30 days all together, never had a contact with coding before. Any contact. But I know what are build-in functions and I am well aware of the obvious solution you gave. Still, like I said, I needed to solve it with a loop and it may be wrong or logically inconsistent, but it was the best I could do at the moment. Anyway, I did share it to get criticized since it’s the only way I can get feedback, so knock yourself out :slight_smile:

1 Like

Btw, these were the challenge instructions.

Instructions

1.

Create a function named max_num() that takes a list of numbers named nums as a parameter.

The function should return the largest number in nums

Hint

Create a variable called maximum to track the max number, and have it start as the first element in the list. Loop through all of the numbers in the list, and if a number is ever greater than the current max number, the max number should be re-set to that number.

We are expected to iterate over a list and return the largest number. How do we iterate over a list?

  • for
  • while

It follows we would start with an initial value for maximum, whether we take it from the list, or just initialize with 0 (zero).

maximum = 0
for num in nums:
    if ...:
        maximum = num
1 Like