
September 11th, 2008, 02:30 PM
|
 | Expert | | Join Date: Oct 2006 Location: Nashville, TN
Posts: 1,214
| |
Quote: |
Originally Posted by curien Hello,
I am working on a code that takes the users input ( a string of digits) from the command line and prints out the median number. I am trying to accomplish this by:
from sys import argv
nums = argv[1:]
for index, value in enumerate(nums):
nums[index] = float(value)
print nums[1:] + nums[:1] / 2
I keep getting the error:
type error: unsupported operand type(s) for /: 'list' and 'int' | First, let's consider the definition of the median number of a sequence of numbers. The median is the number where half of the numbers are larger and half are smaller. Therefore the list must be sorted. If the list contains an even number of items, the median is taken as the mean or average between the two middle numbers. The following function returns the median number from a sorted list of numbers: - def median(s):
-
i = len(s)
-
if not i%2:
-
return (s[(i/2)-1]+s[i/2])/2.0
-
return s[i/2]
Example: - >>> s1 = "100 45 89 23 105 220 45 66 8 75"
-
>>> s2 = "100 45 89 23 105 220 45 66 8 75 7"
-
>>> sList = [float(num) for num in s1.split()]
-
>>> sList.sort()
-
>>> median(sList)
-
70.5
-
>>> sList
-
[8.0, 23.0, 45.0, 45.0, 66.0, 75.0, 89.0, 100.0, 105.0, 220.0]
-
>>> sList = [float(num) for num in s2.split()]
-
>>> sList.sort()
-
>>> median(sList)
-
66.0
-
>>> sList
-
[7.0, 8.0, 23.0, 45.0, 45.0, 66.0, 75.0, 89.0, 100.0, 105.0, 220.0]
-
>>>
|