-2

I know it's probably a stupid question, but I did my research and I didn't find anything that could solve it. I would love it if anybody could help me.

I am trying to index the day of the week with the right min() and max()

Monday= input('Enter the temperature for monday:')
Tuesday= input('Enter the temperature for Tuesday:')
Wednesday= input('Enter the temperature for Wednesday:')
Thrusday= input('Enter the temperature for Thrusday:')
Friday= input('Enter the temperature for Friday:')

list=[Monday, Tuesday, Wednesday, Thursday, Friday]

for i in list:
    print(f" Tuesday was the coldest day with the temperature: {min(list)}")
    print(f"Tuesday was the warmest day with the temperature: {max(list)}")
    break

Thanks Anyway!

1 Answers1

0

This is a variation on this question: Find maximum value and index in a python list? (the answer posted there might be a little difficult for someone brand new to follow, so I will expand below rather than marking as duplicate).

You want to keep your data together as much as possible. Otherwise if you sort the list - which would be simplest way to find out what the highest temperature was without tracking which day of the week it was - when you do the sort it will lose order.

Note: Do not call a variable "list". You will have all kinds of problems.

Note: For anything significant I would write a class and include custom comparator functions (equals, less than, greater than).

list_of_days = [['Monday',20], ['Tuesday',22], ['Wednesday',16], ['Thursday',24], ['Friday',22]]

In order to keep track of the position in the list and write the new temperature back to the list, enumerate should be used.

for di,d in enumerate(list_of_days):
    day_prompt = f'Enter the temperature for {d[0]}: '
    day_temp = input(day_prompt)
    list_of_days[di][1] = int(day_temp)

Now an updated list is present. Note this will fail is anything other than a number is entered.

hottest_day = max(list_of_days, key=lambda item: item[1])
print(f'{hottest_day[0]} was the hottest day of the week with a temperature of {str(hottest_day[1])}')

The crucial part of this is the key parameter, in order to tell the max function to use the second element to compare contents of the list.

Alan
  • 2,914
  • 2
  • 14
  • 26
  • Interesting! Quick question! Why did you assign values to the day of the week even tho you just used the values from the input? – mluanastevens Nov 23 '20 at 08:21
  • I am learning a lot from your answer! Thank you so much! – mluanastevens Nov 23 '20 at 08:46
  • @MichelleStevens For two reasons. Mainly for clarity to show that it is a list of lists (it would end up that way anyway so why not start off that way) and also to make it clear that the temperature value should be an integer, not a string. If the posted details answer your question, please mark it as the accepted answer. – Alan Nov 23 '20 at 16:49