Courses/Computer Science/CPSC 203/CPSC 203 Template/Fall 2009 Teaching Assistants/F09 Thomas Burt/Programming Review

From wiki.ucalgary.ca
Jump to: navigation, search

Review

The format of Quiz #3 will be different than the last two. To help prepare, we're going to go through the following tasks.

Code Repair

Fix the following function so that it works:

def average( list )
  total = 0
  length = len( list )
  for x in list:
    total += length

  return total/length


Here's another one to fix in case you get bored:

def do( list ):
  for i in list
    if( i % 2 = 0):
      print( "odd: " + str(list))
    else:
      print( "even: " + str(list))

Code Modify

Often, existing code works fine but needs to be modified so that it does something different.

Imagine that we need to raise prices for certain items in our coffee shop. Our cash register has a function that takes in a string representing a menu item, and returns the price:

def calculate_price( item):
  if item == "coffee":
    return 3.25
  elif item == "tea":
    return 2.85
  elif item == "bagel":
    return 5.20
  elif item == "sandwich":
    return 12.75
  elif item == "apple":
    return 2.25

Complete the following modifications:

  • raise all existing drink prices by 2.5% and all food prices by 4%.
  • add an item called "latte". It should cost $6.75.

Code Write

Write a function called AverageOfEvens.

The input to the function is a list of numbers. The output is the average of all the numbers that are even.

For instance, if my input is
[1,2,3,4]
then the output is
3
because only two (2) and four (4) are even, and the average between the two is three (3).


You will need the following tools to make this work:

  • Function Definition
  • For Loop to access elements of the list
  • If Statement to test if the list element even
    • Use can use the following function:
def is_even( number ):
  return ( number % 2 ) == 0


More Review

/ Exercises

/ Answers