简体   繁体   中英

How to find the median?

I am trying to create a function that can get any number of inputs and find the median. I feel like I am going about this all wrong, I cannot get this functional.
What do I need to do?

  1. I made my list
  2. I asked user for inputs
  3. I sorted with numpy
  4. I printed median

Code:

import numpy

numbers = [1,2,3]                
1 = input("Please type your first number")            
2 = input("please type your second number")       
3 = input("please type your third number")       
median = numpy.median(numbers)            
print(median) 

What I am trying to accomplish:

What numbers would you like to find the median for? 1,2,3,4,5,6,7
The median is: 4

You should store the numbers in a list, and use a loop to add numbers to it.

import numpy

size = int(input("Enter number of numbers you would like to enter"))
numbers = []
for i in range(size):
    numbers.append(int(input("Please type in number %d" % i)))

median = numpy.median(numbers)  

print(median) 

Your approach fails because you try to use numbers as variable names, which is not valid.

You cannot assign values to 1, 2, or 3. Additionally, you need to convert the strings from input to int s. Try some simple changes.

import numpy                
input1 = input("Please type your first number")            
input2 = input("Please type your second number")       
input3 = input("Please type your third number")
numbers = map(int, [input1, input2, input3])
median = numpy.median(numbers)            
print(median) 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM