简体   繁体   中英

Using loops to find the highest score, lowest score from a list

Update: It seems that I understood the directions for the code wrong.

Absolutely new to Python, so any help is appreciated.

I am trying to find the highest score and the lowest score from an array using loops.

Here is the code I worked on:

nums = [6, 8, 9, 5, 3, 3, 5, 3]
highest_score = []
lowest_score = []

def calculate_Scores(nums):
  i = 1
  max = min = nums[0]
  if nums[0] > nums[1]:
    highest_score.append(nums[0])
  elif nums[0] < nums[1]:
    lowest_score.append(nums[0])
  while i < len(nums):
    if nums[i] > max:
      highest_score.append(nums[i])
    if nums[i] < min:
      lowest_score.append(nums[i])
    i += 1

 calculate_Scores(nums)
 print(highest_score)
 print(lowest_score)

Output:

 [8, 9] #highest
 [6, 5, 3, 3, 5, 3] #lowest

The code works just fine for the array given above, but when you change the array nums to:

[2, 8, 9, 5, 3, 3, 5, 3]

This is the output:

[8, 9, 5, 3, 3, 5, 3] #highest
[2] #lowest

How can I make it work so that 3 also goes to the variable lowest_score? Is there any other way I can make this whole process work? (Without using max() and min())

If you're trying to find the highest number, why do you append to highest_score or lowest_score constantly? Wouldn't you want to only append the maximum or minimum? Why not calculate them first?

nums = [6, 8, 9, 5, 3, 3, 5, 3]
highest_score = []
lowest_score = []

def calculate_Scores(nums):
  i = 1
  max = min = nums[0]
  # first, calculate the max and min.
  while i < len(nums):  # (possible improvement: replace this with a for loop)
    if nums[i] > max:
      max = nums[i]    # replace max with the new max
    if nums[i] < min:
      min = nums[i]    # replace min with the new min
    i += 1
  # now that you've done that, add them to the highest_score and lowest_score
  highest_score.append(max)
  lowest_score.append(min)

Note that while this may be a useful educational exercise, there's no practical reason to not just use the built-in functions max() and min() in this situation (or really any other situation where you're trying to find the one element that out-competes others in some way).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM