This page is located in archive. Go to the latest version of this course pages. Go the latest version of this page.

Computer Lab 07, comprehensive exercises

Character triangles

Ex. 1: Using nested loops, write function print_left_triangle(n_rows, char) which prints the triangle depicted below. E.g. when you call that function like this:

>>> print_left_triangle(n_rows=5, char='T')

Ex. 2: Again, using nested loops, write function print_right_triangle(n_rows, char) which prints the triangle depicted below. E.g. when you call that function like this:

>>> print_right_triangle(n_rows=5, char='T')

Lists and dictionaries

Ex. 3: Write a Python script to generate and print a dictionary that contains a number (between 1 and n) in the form (x, x*x). Expected output for n = 5: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Ex. 4: Get the key corresponding to the minimum value from the following dictionary

sampleDict = {
  'Physics': 82,
  'Math': 65,
  'History': 75

Weekly homework 07 - Combining dictionaries

Ex. 5: Write a Python function combine_dict(d1, d2) to combine two dictionary adding values for common keys.

d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}
# expected return value - output dictionary
#{'a': 400, 'b': 400, 'd': 400, 'c': 300}
Required filename: 07_weekly_hw.py.

Ex. 6: Given the following dictionary:

inventory = {
    'gold' : 500,
    'pouch' : ['flint', 'twine', 'gemstone'],
    'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']
Try to do the followings:

  • Add a key to inventory called 'pocket'.
  • Set the value of 'pocket' to be a list consisting of the strings 'seashell', 'strange berry', and 'lint'.
  • .sort()the items in the list stored under the 'backpack' key.
  • Then .remove('dagger') from the list of items stored under the 'backpack' key.
  • Add 50 to the number stored under the 'gold' key.

Control Flow

Ex. 7: Write a program to prompt the user for hours and rate per hour to compute gross pay. Take into account that the factory gives the employee 1.5 times the hourly rate for hours worked above 40 hours.

Enter Hours: 45
Rate: 10
Pay: 475.0

Ex. 8: Pig Latin is a language game, where you move the first letter of the word to the end and add “ay.” So “Python” becomes “ythonpay.” To write a Pig Latin translator in Python, here are the steps we'll need to take:

  • Ask the user to input a word in English.
  • Make sure the user entered a valid word.
  • Convert the word from English to Pig Latin.
  • Display the translation result.
courses/be5b33prg/labs/week_07.txt · Last modified: 2020/11/05 14:12 by nemymila