Homework Assignment

Your homework assignment this week is to write a function called 'average'. it takes a list as input and returns the arithmetic average. You should assume the list only contains numbers.

It should have a docstring explaining what it does (hint: """text""").

Hints:

  • len(input) will give you the length of the list.
  • sum(input) will add everything up.
  • If the list is empty, return the string "EMPTY LIST"

FOR BONUS POINTS

  • You are ONLY allowed to use addition and for-loops (The use of LEN and SUM is not allowed!).

The bonus problem is a bit tricky but I believe in you guys. Good luck!

Possible Solution (easy)


In [11]:
def average(L):
    """L is a list, we return the average of L (a float)"""
    if not L:
        return "EMPTY LIST"
    return sum(L)/len(L)

Possible Solution (hard)


In [10]:
def average2(L):
    """L is a list, we return the average of L (a float)"""
    if not L:
        return "EMPTY LIST"
    
    total = 0  
    length = 0
    for num in L:
        total += num
        length +=1
    
    return total / length