Practice Problems 3 For the week of 2020-02-24

The following exercises provide additional practice problems (not to turn in) for our material this week. Try to solve each problem on paper / whiteboard first before using Thonny to confirm your answers. You are encouraged to work on these practice exercises with classmates throughout the week.

  1. [PP Problem 7.11] Using string methods, write Python expressions that produce the following (just the expression, you don’t need to write a function). You should be able to accomplish all of these tasks with just one or more string methods.

    a. A copy of ‘boolean’ capitalized
    b. The index of the first occurrence of ‘2’ in ‘CO2 H2O’
    c. The index of the second occurrence of ‘2’ in ‘CO2 H2O’
    d. True if and only if ‘Boolean’ begins with a lowercase letter
    e. A copy of “MoNDaY” converted to lowercase and then capitalized
    f. A copy of “ Monday” with the leading whitespace removed

  2. Evaluate the following expressions assuming the variable digits has the value “0123456789”, i.e. the string containing the digits 0-9.

    a. digits[:5]
    b. digits[5:]
    c. digits[::2]
    d. digits[1::2]
    e. digits[-5:-3]

  3. Write a function named last_half that takes a string as a parameter and returns the last half of that string. For odd length strings, you may round either way.

  4. Write a function named insert_noise(word) that returns a new string with the letter “a” inserted after each letter in the original string. For example:

     >>> insert_noise('abc')
     'aabaca'
     >>> insert_noise('Hi there!')
     'Haia atahaearaea!a'
    
  5. Extend your insert_noise function from above to insert a random letter from the alphabet after each letter in the original string. Assume that like Lab 3 you have the following constant defined in your program.

    ALPHABET="abcdefghijklmnopqrstuvwxyz "
    

    For example:

    >>> insert_noise('abc')
    'anbecf'
    >>> insert_noise('Hi there!')
    'Hyie ctmhceprten!q'
    
  6. As a bonus challenge, further extend your insert_noise function to only insert letters between letters in the original word. Your function should work if the original word is the empty string. As a hint, slice operations on the empty string evaluate to the empty string. For example:

     >>> insert_noise('abc')
     'anbec'
     >>> insert_noise('Hi there!')
     'Hyie ctmhceprten!'
     >>> insert_noise('')
     ''