Home > Enterprise >  Lists and Loops in Python
Lists and Loops in Python

Time:11-13

I am trying to find a maximum/minimum value corresponding to a day.

list1 includes all 7 days of the week. list two is empty [] I have a loop that iterates as many times as the len of list 1,(7), which asks the user to input how many hours they did an activity each day. how can I print the day that has the max/min value??

count = 0
list1 = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

list2 = []
total = 0
for x in range(len(list1)):
    try:
        num = float(input(f"Enter amount of hours of exercise for {list1[x]}: "))
        list2.append(num)
        total  = num
    except:
        print("Please enter a number.")
        sys.exit()
    total = sum(list2)

#THESE LINES ARE WHERE I AM HAVING DIFFICULTY!

mamimum = max(list2[list1])
minimum = min(list2[list1])                

print("Day with most amount of exercise: ", maximum)
print("Day with least amount of exercise: ", minimum)

CodePudding user response:

Simply create a dictonary by zipping them out of values print max and min key value pairs

count = 0
import sys
list1 = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

list2 = []
total = 0
for x in range(len(list1)):
    try:
        num = float(input(f"Enter amount of hours of exercise for {list1[x]}: "))
        list2.append(num)
        total  = num
    except:
        print("Please enter a number.")
        sys.exit()
    total = sum(list2)

#THESE LINES ARE WHERE I AM HAVING DIFFICULTY!
print(list2)
zipper =dict(zip(list1, list2))         

print("Day with most amount of exercise: ",  [k for k, v in zipper.items() if v == max(zipper.values())])
print("Day with least amount of exercise: ",  [k for k, v in zipper.items() if v == min(zipper.values())])

output #

Day with most amount of exercise:  ['Sunday', 'Monday']
Day with least amount of exercise:  ['Tuesday']

CodePudding user response:

Once you have list1 and list2 (which are not very successfull names), what you want is the index of the maximal/minimal value of list2. This is called argmax/argmin respectively, and can be obtained easily using np.argmax (or np.argmin).
However, it's also simple using "clean" python, with no unnecessary imports, for instance by using the key argument of the built-in max (min) function:

max_index = max(range(7), key=lambda i: list2[i])
min_index = min(range(7), key=lambda i: list2[i])

And if you've got the index, then you've got your max/min day and amount:

print(f'Maximal amount of exercise was {list2[max_index]}, which was obtained on {list1[max_index]}')
print(f'Minimal amount of exercise was {list2[min_index]}, which was obtained on {list1[min_index]}')

On an unrelated note, notice than you don't need to loop over range(len(list1)), if you're doing that just so you get indexes with which you then use list1[x]. You can just directly loop over list1.
So your code would be a little better as follows (changing names while I'm at it):

count = 0
week_days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

exercise_amounts = []
total = 0
for wd in week_days:
    try:
        num = float(input(f"Enter amount of hours of exercise for {wd}: "))
        exercise_amounts.append(num)
        total  = num
    except:
        print("Please enter a number.")
        sys.exit()
    total = sum(exercise_amounts)

max_index = max(range(7), key=lambda i: exercise_amounts[i])
min_index = min(range(7), key=lambda i: exercise_amounts[i])

print(f'Maximal amount of exercise was {exercise_amounts[max_index]}, which was obtained on {week_days[max_index]}')
print(f'Minimal amount of exercise was {exercise_amounts[min_index]}, which was obtained on {week_days[min_index]}')

CodePudding user response:

First you can find the index of maximum and minimum in list 2, then print the values in list 1:

count = 0
list1 = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

list2 = []
total = 0
for x in range(len(list1)):
    try:
        num = float(input(f"Enter amount of hours of exercise for {list1[x]}: "))
        list2.append(num)
        total  = num
    except:
        print("Please enter a number.")
    total = sum(list2)
    

#THESE LINES ARE WHERE I AM HAVING DIFFICULTY!
max_index = list2.index((max(list2)))
min_index = list2.index((min(list2)))

print("Day with most amount of exercise: ", list1[max_index])
print("Day with least amount of exercise: ", list1[min_index])

If you have more than one value for Max or Min:

max_days = [list1[i] for i, j in enumerate(list2) if j == max(list2)]
min_days = [list1[i] for i, j in enumerate(list2) if j == min(list2)]

print("Day with most amount of exercise: ", max_days)
print("Day with least amount of exercise: ", min_days)

CodePudding user response:

Your approach also works pretty well. Here's the fix on your approach:

count = 0
list1 = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

list2 = []
total = 0
for x in range(len(list1)):
    try:
        num = float(input(f"Enter amount of hours of exercise for {list1[x]}: "))
        list2.append(num)
        total  = num
    except:
        print("Please enter a number.")
        sys.exit()
    total = sum(list2)
maximum = max(list2) # gets the max value corresponding to list2
minimum = min(list2) # gets the min value corresponding to list2
# Compatibility for two max/min values:
def moreThanTwo(value, lst):
    return [i for i, j in enumerate(lst) if j == value] # returns the index with max/min values
maximum = [list1[idx] for idx in moreThanTwo(maximum, list2)] # gets the max values
minimum = [list1[idx] for idx in moreThanTwo(minimum, list2)] # gets the min values
print(f"Day with most amount of exercise: {', '.join(maximum)}")
print(f"Day with least amount of exercise: {', '.join(minimum)}")

However, I would suggest using a dictionary approach like this:

days = {"Sunday": 0, "Monday": 0, "Tuesday": 0, "Wednesday": 0, "Thursday": 0, "Friday": 0, "Saturday": 0} # day : time
for key, value in days.items():
    try:
        days[key] = float(input(f"Enter amount of hours of exercise for {key}: ")) # update value in dict
    except:
        print("Please enter a number.")
        exit() # you don't need sys.exit()

maximum = max(days.values()) # gets the max value corresponding to days
minimum = min(days.values()) # gets the min value corresponding to days
# Compatibility for two max/min values:
def moreThanTwo(value, days):
    return [k for k, v in days.items() if v == value] # returns the day with max/min values
maximum =  moreThanTwo(maximum, days) # gets the max values
minimum = moreThanTwo(minimum, days) # gets the min values
print(f"Day with most amount of exercise: {', '.join(maximum)}")
print(f"Day with least amount of exercise: {', '.join(minimum)}")
  • Related