Advertisements
when I run this code it adds to the list so I can’t find the median. How would I make it so empty values do not get added to the list
import statistics
import time
amount=int(input('How many marks are you going to
input? (most 10) '))
while amount>10:
print('No')
time.sleep(1)
else:
print(amount)
input_string=input('Enter marks of students
separated by a space: ')
print('\n')
user_list = input_string.split()
print('list: ', user_list)
user_list=map(int, user_list)
print('Mean = ', sum(user_list)/amount)
sorted_string=sorted(input_string)
print(sorted_string)
new=(amount+1)//2
print(new)
median=sorted_string[new]
print(median)
>Solution :
First issue
You are iterating through a map more than once, which leaves you with a bug of sorting an empty collecting.
(I suggest you read more about it: map()
returns an iterator)
to demonstrate the issue:
my_map = map(int, ['1', '2', '3'])
print('first run')
for i in my_map:
print(i)
print('second run')
for i in my_map:
print(i)
output:
first run
1
2
3
second run
Second issue
You are passing input_string
to sorted()
instead of user_list
which is what I assume you want?
Example
Fixing (1) and (2) will result in the expected output:
import statistics
import time
amount=int(input('How many marks are you going to input? (most 10) '))
while amount>10:
print('No')
time.sleep(1)
else:
print(amount)
input_string=input('Enter marks of students separated by a space: ')
print('\n')
user_list = input_string.split(' ')
print('list: ', user_list)
user_list=list(map(int, user_list))
print('Mean = ', sum(user_list)/amount)
sorted_string=sorted(user_list)
print(sorted_string)
new=(amount+1)//2
print(new)
median=sorted_string[new]
print(median)`
dialogue:
How many marks are you going to input? (most 10) 2
2
Enter marks of students separated by a space: 100 95
list: ['100', '95']
Mean = 97.5
[95, 100]
1
100
Side notes
Outside the context of your question, consider:
- Taking the amount from the given list, instead of requesting for an amount explicitly
- If the amount given is
>10
, then there is an infinite loop saying ‘No’. Just making sure this is intentional.