Home > other >  How to iterate through a loop to find highest value in a list? (python)
How to iterate through a loop to find highest value in a list? (python)

Time:11-15

I am tasked with creating two functions one that creates a list of 10 random integers and the other is supposed to find the highest number in the list using a loop (without using the max option). I am having difficulty with the second function (getHighest). Nothing is being returned/printed and I am also not getting an error. Please help!

Here is what I have tried:

from random import randint

def main() :
  MIN = -100
  MAX = 100
  LIST_SIZE = 10
  scores = []
  for i in range(LIST_SIZE):
    scores.append(randint(MIN, MAX))
  print(scores)
 
def getHighest(scores) :
  highest = scores[0]
  for score in range(0,len(scores)) :
    if highest < score:
      highest = score
  print(f"Highest value: {highest}")
 
main()

CodePudding user response:

Your code is almost done. There are some ways to fix it:

Get the n-th element from the list:

 scores[score]

This code probably works, but it's not the python way of doing things. Let's make some changes:

range(len(scores))

The range function takes at least one parameter: the stop value. If you pass just a single parameter, the default start value is 0 and the step is 1. However this is not the best way to do it in the Python world.

The for statement traverses an iterable. Range returns a sequence of numbers. But you can traverse the scores parameter itself. And the score variable will now hold the actual value instead of an index:

    for score in scores :

If you need the value and the index, you can use the enumerate function:

    for ind, score in enumerate(scores) :

There's another way to get the max value of a list without the max function: if you have memory to spare, you can just make a copy of your list, sort the copy and get the last element (the -1 index):

    sorted_list = sorted(scores)

Better yet: you can get the sorted list in the reversed order by adding the parameter reverse=True and now looking at the first element (0) instead of the last:

    sorted_list = sorted(scores, reverse=True)

As some commentators noted, in order to use the getHighest function you need to call it:

   def main():
       # ... 
       print(scores)
       getHighest(scores)

Finally,I highly advise to read Python documentation available at https://docs.python.org. For instance, you can use List Comprehensions to generate the random number list.

CodePudding user response:

I previously worked on this same thing! I hope this might help. In addition to previous commenters I would also recommend W3schools at this link

def getHighest():
    highest = scores[0]
    for i in range(len(scores)):
        if score[i]>highest
            highest=scores[i]
    print("Highest value is:" highest)
  • Related