Teaching Kids Programming – Compute the Average and Median


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.

1
2
3
4
5
def average(nums):
  s = 0
  for i in nums:
    s += i
  return s / len(nums)
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):

1
2
def average(nums):
  return sum(nums) / len(nums)
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

1
2
3
4
5
6
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
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) —

GD Star Rating
loading...
293 words
Last Post: Algorithms to Check Narcissistic Number
Next Post: Using a Hash Table to Find A Number and Its Triple in a List

The Permanent URL is: Teaching Kids Programming – Compute the Average and Median

Leave a Reply