I am currently studying python, and I am struggling to find an answer to an assignment. I need to create a list from a user input, then find the highest temperature of the input and count how many times that temperature appears from the input. Finally I should output the highest temperature and how many times it appears.
input_temps = []
for i in range(int(input("Enter the tmeperature here: "))):
input_temps.append(int(input()))
print(input_temps)
this is what I have so far.
Edit: I am not allowed to use any max or count functions
(Note: This was before they changed the question to rule out those functions, but a solution without is at the end)
You can use max
and count
functions. And better improve the input messages:
input_temps = []
for i in range(int(input("Enter the number of temperatures: "))):
input_temps.append(int(input("Enter a temperature: ")))
print(input_temps)
max_temp = max(input_temps)
print(f'{max_temp=}')
max_temp_count = input_temps.count(max_temp)
print(f'{max_temp_count=}')
Demo:
Enter the number of temperatures: 3
Enter a temperature: 5
Enter a temperature: 4
Enter a temperature: 5
[5, 4, 5]
max_temp=5
max_temp_count=2
Since you now asked for a version without using max
:
input_temps = []
max_temp = None
max_temp_count = None
for i in range(int(input("Enter the number of temperatures: "))):
temp = int(input("Enter a temperature: "))
input_temps.append(temp)
if max_temp is None or temp > max_temp:
max_temp = temp
max_temp_count = 1
elif temp == max_temp:
max_temp_count += 1
print(f'{max_temp=}')
print(f'{max_temp_count=}')
Another possibility is to enter all the temperatures, either space or comma separated:
temps = input('Enter the temperatures here: ')
temps_list = [float(s) for s in temps.split(',')]
hg = max(temps_list)
cnt = temps.count(hg)
print(f'List of temperatures: {temps}\
\nThe highest temperature is {hg}, which appears {cnt} times.')
Working example:
Enter the temperatures here: 3,1.1,2,3.2,6,2.2,6,5.7,5
List of temperatures: [3.0, 1.1, 2.0, 3.2, 6.0, 2.2, 6.0, 5.7, 5.0]
The highest temperature is 6.0, which appears 2 times.
To find the max temperature in the list, just use max(input_temps)
. After that, you can set up a counter variable starting at 0 and use a for loop that iterates through each element in the list and compares it to the max temperature. If they are equal, just add 1 to the counter.
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.