Teaching Kids Programming: Videos on Data Structures and Algorithms
Compute the Average
The average of some numbers can be comptued as the sum of them divided by the number of elements. For example, the average of 4 and 6 is calculated as (4+6)/2=5.
Here is a Python function to compute the average.
def average(nums):
s = 0
for i in nums:
s += i
return s / len(nums)
Python already provides the sum function, and thus the above can be simplified to this (avoid re-invent the wheel):
def average(nums):
return sum(nums) / len(nums)
Compute the Median
The median is defines as the middlest number (if there are odd number of elements) or the average of the two middlest number (if there are even number of elements) in the sorted list.
For example, 3, 4, 5 the median is 4 and 3, 4, 5, 6 the median is (4+5)/2=4.5
def median(nums):
nums.sort()
sz = len(nums)
if sz % 2 == 0: # even number
return (nums[sz//2] + nums[sz//2 - 1]) / 2
return nums[sz//2] # odd number of elements
–EOF (The Ultimate Computing & Technology Blog) —
276 wordsLast Post: Algorithms to Check Narcissistic Number
Next Post: Using a Hash Table to Find A Number and Its Triple in a List