Computation and Cognition - Fall 2006

Homework 3

Due by class time Wednesday, September 27

Reading

Programming Problems

  1. Study the string-manipulation programs we developed in class this week and make sure you understand them.

  2. Work through sections 4.4.2 and 4.4.3 of your textbook (pages 89-94) by typing in the example programs text2numbers and numbers2text. Test out the programs interactively in Python and make sure you understand how they work.

  3. Do problem 3 on page 118 of the textbook. Hint: Keep track of the possible grades in a list, where the position of a grade in the list corresponds to its point value. Use the number entered by the user as an index into this list in order to retrieve the appropriate grade. Call your program grade().

  4. The built-in Python function ord (short for "ordinal") can be used to convert a single letter or other character into an equivalent numeric value called that character's ASCII code, which is just an integer in the range 0-126. Similarly, the function chr (short for "character") converts an ASCII code number back into the equivalent character. This technique can be used to encode and decode strings of characters as lists of numbers.

    Using this idea, do problem 6 on page 119 of the textbook. You'll have to convert upper or lower case letters in the range a to z into numbers in the range 1 to 26. One way is to first convert the letter to uppercase using string.upper(), then convert that to an ASCII code using ord, and then subtract 64, since the ASCII code for A is 65, B is 66, C is 67, and so on. Call your program nameVal().

  5. Do problem 7 on page 119. Call your program fullnameVal(). Hint: Reuse the code you wrote for problem 6, which computes the numeric value of an individual name, but embed it within an outer for-loop, which cycles through each name in the full name entered by the user. In other words, you'll have a for-loop within a for-loop!

  6. Do problem 8 on page 119: Caesar ciphers. Call your program cipher(). To encode a message, use a positive key value; to decode use a negative key. For example:

    >>> cipher()
    Enter a message: Sourpuss
    Enter a key: 2
    The encoded message is:
    Uqwtrwuu
    >>> cipher()
    Enter a message: Uqwtrwuu
    Enter a key: -2
    The decoded message is:
    Sourpuss
    
  7. Problem 12 on page 120: string formatting. Call your program chaos(). Try to make your program's output look exactly like the output shown in the book.

Turning in Your Homework

Put all of your program definitions into a single file called assign3.py. You do not need to include text2numbers or numbers2text from part 2. Print out this file and turn it in to me in class on Wednesday. If you have questions about anything, don't hesitate to ask!