In: Computer Science
Using python
Create a function that inputs a list of numbers and outputs the
median of the numbers.
sort them and them show the output.
SOLUTION:
NOTE: Explanation is done in the code itself, Reading the data can be done in other ways also take the number of items, and loop through and read the data. I have used a one-line statement to read the data. Don't give space at the end while entering the data since it will through an error if we give space since if we give space split will separate using space so that it will create an empty item at end of the list since we are doing the int conversion it will through error, So i am also providing another way or reading data also.
CODE:
##defining the function which takes the list as an input and
checks the median
def median(data):
##sort method is used to sort data of list
data.sort()
##printing the data to check whether it is sorted or not
print(data)
if(len(data)/2!=0):
##if there are an odd number of items then the middle term is
median
print("Median is ",data[len(data)//2])
else:
##if there are even number of items then median is the average of
middle-term and its next term
print("Median is ",(data[len(data)//2]+data[len(data)//2])/2)
##reading the data in a single line separated by spaces
##we are using split to separate string apart and then by the map
we are converting it to integer since it is the map we need to
convert it to list
data=list(map(int,input("Enter numbers ").split(" ")))
##call the function median to get the median
median(data)
SOLUTION:
OUTPUT:
ANOTHER WAY OF READING DATA AND CONVERTING TO INT :
def median(data):
##sort method is used to sort data of list
data.sort()
##printing the data to check whether it is sorted or not
print(data)
if(len(data)/2!=0):
##if there are odd number of items then middle term is median
print("Median is ",data[len(data)//2])
else:
##if there are even number of items then medaian is the average of
middle term and its next term
print("Median is ",(data[len(data)//2]+data[len(data)//2])/2)
##reading data
data=input("Enter numbers ").split(" ")
##creating empty list to store data
data1=[]
for i in range(len(data)):
##if data is not space we need to append it to the list converting
it to int
##we are doing this to avoid any extra spaces that are given during
entering data
if(data[i]!=''):
data1.append(int(data[i]))
##call median
median(data1)
CODE IMAGE:
OUTPUT: