Python Code Challenges: Loops (Advanced): #3 Max Num

Link:
https://www.codecademy.com/paths/computer-science/tracks/cspath-cs-101/modules/cspath-code-challenges/articles/advanced-python-code-challenges-loops

My solution:

def max_num(lstOfNums):
  max = lstOfNums[0]
  for index in range(1, len(lstOfNums)):
    if lstOfNums[index] > max:
      max = lstOfNums[index]
  return max

Suggested Solution:

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

Question:
Since the max was set to the 0th element, there is no need to check that one again like in the solution. I used a range that omits 0. Would the range function use more or less resources than redundantly checking the max against the 0 index?

Thanks

I’d say it’s about the same, really. Yes, you’re avoiding one case, but that won’t really affect much in terms of memory/time. I’d say that the suggested solution is “better” just because it’s more readable than yours because it doesn’t involve finding every element by its index.


If you really wanted to avoid checking the first element, but wanted to use CC’s solution, you could do something with .pop():

def max_num(nums):
  maximum = nums.pop(0)
etc...
2 Likes