9.12. Exercises

  1. What is the result of each of the following:

    1. ‘Python’[1]

    2. “Strings are sequences of characters.”[5]

    3. len(“wonderful”)

    4. ‘Mystery’[:4]

    5. ‘p’ in ‘Pineapple’

    6. ‘apple’ in ‘Pineapple’

    7. ‘pear’ not in ‘Pineapple’

    8. ‘apple’ > ‘pineapple’

    9. ‘pineapple’ < ‘Peach’

    1. ‘Python’[1] = ‘y’

    2. ‘Strings are sequences of characters.’[5] = ‘g’

    3. len(‘wonderful’) = 9

    4. ‘Mystery’[:4] = ‘Myst’

    5. ‘p’ in ‘Pineapple’ = True

    6. ‘apple’ in ‘Pineapple’ = True

    7. ‘pear’ not in ‘Pineapple’ = True

    8. ‘apple’ > ‘pineapple’ = False

    9. ‘pineapple’ < ‘Peach’ = False

    Show Comments
  2. In Robert McCloskey’s book Make Way for Ducklings, the names of the ducklings are Jack, Kack, Lack, Mack, Nack, Ouack, Pack, and Quack. This loop tries to output these names in order.

    prefixes = "JKLMNOPQ"
    suffix = "ack"
    
    for p in prefixes:
        print(p + suffix)
    

    Of course, that’s not quite right because Ouack and Quack are misspelled. Can you fix it?

    (ex_8_2)

  3. Assign to a variable in your program a triple-quoted string that contains your favorite paragraph of text - perhaps a poem, a speech, instructions to bake a cake, some inspirational verses, etc.

    Write a function that counts the number of alphabetic characters (a through z, or A through Z) in your text and then keeps track of how many are the letter ‘e’. Your function should print an analysis of the text like this:

    Your text contains 243 alphabetic characters, of which 109 (44.8%) are 'e'.
    

    (ex_8_3)

    25
     
    1
    def count(p):
    2
        lows = "abcdefghijklmnopqrstuvwxyz"
    3
        ups =  "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    4
    5
        numberOfe = 0
    6
        totalChars = 0
    7
        for achar in p:
    8
            if achar in lows or achar in ups:
    9
                totalChars = totalChars + 1
    10
                if achar == 'e':
    11
                    numberOfe = numberOfe + 1
    12
    13
        percent_with_e = (numberOfe / totalChars) * 100
    14
        print("Your text contains", totalChars, "alphabetic characters of which", numberOfe, "(", percent_with_e, "%)", "are 'e'.")
    15
    16
    17
    p = '''
    18
    "If the automobile had followed the same development cycle as the computer, a
    19
    Rolls-Royce would today cost $100, get a million miles per gallon, and explode
    20
    once a year, killing everyone inside."
    21
    -Robert Cringely
    22
    '''
    23
    24
    count(p)
    25

    (str_q3_answer)

    Show Comments
  4. Print out a neatly formatted multiplication table, up to 12 x 12.

    (ex_8_4)

  5. Write a function that will return the number of digits in an integer.

    (ex_7_10)

    9
     
    1
    def numDigits(n):
    2
        n_str = str(n)
    3
        return len(n_str)
    4
    5
    6
    print(numDigits(50))
    7
    print(numDigits(20000))
    8
    print(numDigits(1))
    9

    (str_q5_answer)

    Show Comments
  6. Write a function that reverses its string argument.

    (ex_8_5)

  7. Write a function that mirrors its string argument, generating a string containing the original string and the string backwards.

    (ex_8_6)

    16
     
    1
    from test import testEqual
    2
    3
    def reverse(mystr):
    4
        reversed = ''
    5
        for char in mystr:
    6
            reversed = char + reversed
    7
        return reversed
    8
    9
    def mirror(mystr):
    10
        return mystr + reverse(mystr)
    11
    12
    testEqual(mirror('good'), 'gooddoog')
    13
    testEqual(mirror('Python'), 'PythonnohtyP')
    14
    testEqual(mirror(''), '')
    15
    testEqual(mirror('a'), 'aa')
    16

    (str_q7_answer)

    Show Comments
  8. Write a function that removes all occurrences of a given letter from a string.

    (ex_8_7)

  9. Write a function that recognizes palindromes. (Hint: use your reverse function to make this easy!).

    (ex_8_8)

    20
     
    1
    from test import testEqual
    2
    3
    def reverse(mystr):
    4
        reversed = ''
    5
        for char in mystr:
    6
            reversed = char + reversed
    7
        return reversed
    8
    9
    def is_palindrome(myStr):
    10
        if myStr in reverse(myStr):
    11
            return True
    12
        else:
    13
            return False
    14
    15
    testEqual(is_palindrome('abba'), True)
    16
    testEqual(is_palindrome('abab'), False)
    17
    testEqual(is_palindrome('straw warts'), True)
    18
    testEqual(is_palindrome('a'), True)
    19
    testEqual(is_palindrome(''), True)
    20

    (str_q9_answer)

    Show Comments
  10. Write a function that counts how many non-overlapping occurences of a substring appear in a string.

    (ex_8_9)

  11. Write a function that removes the first occurrence of a string from another string.

    (ex_8_10)

    14
     
    1
    from test import testEqual
    2
    3
    def remove(substr,theStr):
    4
        index = theStr.find(substr)
    5
        if index < 0: # substr doesn't exist in theStr
    6
            return theStr
    7
        return_str = theStr[:index] + theStr[index+len(substr):]
    8
        return return_str
    9
    10
    testEqual(remove('an', 'banana'), 'bana')
    11
    testEqual(remove('cyc', 'bicycle'), 'bile')
    12
    testEqual(remove('iss', 'Mississippi'), 'Missippi')
    13
    testEqual(remove('egg', 'bicycle'), 'bicycle')
    14

    (str_q11_answer)

    Show Comments
  12. Write a function that removes all occurrences of a string from another string.

    (ex_8_11)

  13. Here is another interesting L-System called a Hilbert curve. Use 90 degrees:

    L
    L -> +RF-LFL-FR+
    R -> -LF+RFR+FL-
    

    (ex_8_12)

    56
     
    1
    import turtle
    2
    3
    def createLSystem(numIters, axiom):
    4
        startString = axiom
    5
        endString = ""
    6
        for i in range(numIters):
    7
            endString = processString(startString)
    8
            startString = endString
    9
    10
        return endString
    11
    12
    def processString(oldStr):
    13
        newstr = ""
    14
        for ch in oldStr:
    15
            newstr = newstr + applyRules(ch)
    16
    17
        return newstr
    18
    19
    def applyRules(ch):
    20
        newstr = ""
    21
        if ch == 'L':
    22
            newstr = '+RF-LFL-FR+'   # Rule 1
    23
        elif ch == 'R':
    24
            newstr = '-LF+RFR+FL-'
    25
        else:
    26
            newstr = ch     # no rules apply so keep the character
    27
    28
        return newstr
    29
    30
    def drawLsystem(aTurtle, instructions, angle, distance):
    31
        for cmd in instructions:
    32
            if cmd == 'F':
    33
                aTurtle.forward(distance)
    34
            elif cmd == 'B':
    35
                aTurtle.backward(distance)
    36
            elif cmd == '+':
    37
                aTurtle.right(angle)
    38
            elif cmd == '-':
    39
                aTurtle.left(angle)
    40
    41
    def main():
    42
        inst = createLSystem(4, "L")  # create the string
    43
        print(inst)
    44
        t = turtle.Turtle()           # create the turtle
    45
        wn = turtle.Screen()
    46
    47
        t.up()
    48
        t.back(200)
    49
        t.down()
    50
        t.speed(9)
    51
        drawLsystem(t, inst, 90, 5)   # draw the picture
    52
                                      # angle 90, segment length 5
    53
        wn.exitonclick()
    54
    55
    main()
    56

    (str_q13_answer)

    Show Comments
  14. Here is a dragon curve. Use 90 degrees.:

    FX
    X -> X+YF+
    Y -> -FX-Y
    

    (ex_8_13)

  15. Here is something called an arrowhead curve. Use 60 degrees.:

    YF
    X -> YF+XF+Y
    Y -> XF-YF-X
    

    (ex_8_14)

    53
     
    1
    import turtle
    2
    3
    def createLSystem(numIters, axiom):
    4
        startString = axiom
    5
        endString = ""
    6
        for i in range(numIters):
    7
            endString = processString(startString)
    8
            startString = endString
    9
    10
        return endString
    11
    12
    def processString(oldStr):
    13
        newstr = ""
    14
        for ch in oldStr:
    15
            newstr = newstr + applyRules(ch)
    16
    17
        return newstr
    18
    19
    def applyRules(ch):
    20
        newstr = ""
    21
        if ch == 'X':
    22
            newstr = 'YF+XF+Y'   # Rule 1
    23
        elif ch == 'Y':
    24
            newstr = 'XF-YF-X'
    25
        else:
    26
            newstr = ch     # no rules apply so keep the character
    27
    28
        return newstr
    29
    30
    def drawLsystem(aTurtle, instructions, angle, distance):
    31
        for cmd in instructions:
    32
            if cmd == 'F':
    33
                aTurtle.forward(distance)
    34
            elif cmd == 'B':
    35
                aTurtle.backward(distance)
    36
            elif cmd == '+':
    37
                aTurtle.right(angle)
    38
            elif cmd == '-':
    39
                aTurtle.left(angle)
    40
    41
    def main():
    42
        inst = createLSystem(5, "YF")  # create the string
    43
        print(inst)
    44
        t = turtle.Turtle()            # create the turtle
    45
        wn = turtle.Screen()
    46
    47
        t.speed(9)
    48
        drawLsystem(t, inst, 60, 5)    # draw the picture
    49
                                       # angle 90, segment length 5
    50
        wn.exitonclick()
    51
    52
    main()
    53

    (str_q15_answer)

    Show Comments
  16. Try the Peano-Gosper curve. Use 60 degrees.:

    FX
    X -> X+YF++YF-FX--FXFX-YF+
    Y -> -FX+YFYF++YF+FX--FX-Y
    

    (ex_8_15)

  17. The Sierpinski Triangle. Use 60 degrees.:

    FXF--FF--FF
    F -> FF
    X -> --FXF++FXF++FXF--
    

    (ex_8_16)

    59
     
    1
    import turtle
    2
    3
    def createLSystem(numIters, axiom):
    4
        startString = axiom
    5
        endString = ""
    6
        for i in range(numIters):
    7
            endString = processString(startString)
    8
            startString = endString
    9
    10
        return endString
    11
    12
    def processString(oldStr):
    13
        newstr = ""
    14
        for ch in oldStr:
    15
            newstr = newstr + applyRules(ch)
    16
    17
        return newstr
    18
    19
    def applyRules(ch):
    20
        newstr = ""
    21
        if ch == 'F':
    22
            newstr = 'FF'   # Rule 1
    23
        elif ch == 'X':
    24
            newstr = '--FXF++FXF++FXF--'
    25
        else:
    26
            newstr = ch     # no rules apply so keep the character
    27
    28
        return newstr
    29
    30
    def drawLsystem(aTurtle, instructions, angle, distance):
    31
        for cmd in instructions:
    32
            if cmd == 'F':
    33
                aTurtle.forward(distance)
    34
            elif cmd == 'B':
    35
                aTurtle.backward(distance)
    36
            elif cmd == '+':
    37
                aTurtle.right(angle)
    38
            elif cmd == '-':
    39
                aTurtle.left(angle)
    40
    41
    def main():
    42
        inst = createLSystem(5, "FXF--FF--FF")   # create the string
    43
        print(inst)
    44
        t = turtle.Turtle()           # create the turtle
    45
        wn = turtle.Screen()
    46
        t.up()
    47
        t.back(200)
    48
        t.right(90)
    49
        t.forward(100)
    50
        t.left(90)
    51
        t.down()
    52
        t.speed(9)
    53
    54
        drawLsystem(t, inst, 60, 5)   # draw the picture
    55
                                      # angle 90, segment length 5
    56
        wn.exitonclick()
    57
    58
    main()
    59

    (str_q17_answer)

    Show Comments
  18. Write a function that implements a substitution cipher. In a substitution cipher one letter is substituted for another to garble the message. For example A -> Q, B -> T, C -> G etc. your function should take two parameters, the message you want to encrypt, and a string that represents the mapping of the 26 letters in the alphabet. Your function should return a string that is the encrypted version of the message.

    (ex_8_17)

  19. Write a function that decrypts the message from the previous exercise. It should also take two parameters. The encrypted message, and the mixed up alphabet. The function should return a string that is the same as the original unencrypted message.

    (ex_8_18)

    31
     
    1
    def encrypt(message, cipher):
    2
        alphabet = "abcdefghijklmnopqrstuvwxyz"
    3
        encrypted = ''
    4
        for char in message:
    5
            if char == ' ':
    6
                encrypted = encrypted + ' '
    7
            else:
    8
                pos = alphabet.index(char)
    9
                encrypted = encrypted + cipher[pos]
    10
        return encrypted
    11
    12
    def decrypt(encrypted, cipher):
    13
        alphabet = "abcdefghijklmnopqrstuvwxyz"
    14
        decrypted = ''
    15
        for char in encrypted:
    16
            if char == ' ':
    17
                decrypted = decrypted + ' '
    18
            else:
    19
                pos = cipher.index(char)
    20
                decrypted = decrypted + alphabet[pos]
    21
        return decrypted
    22
    23
    24
    cipher = "badcfehgjilknmporqtsvuxwzy"
    25
    26
    encrypted = encrypt('hello world', cipher)
    27
    print encrypted
    28
    29
    decrypted = decrypt(encrypted, cipher)
    30
    print(decrypted)
    31

    (str_q19_answer)

    Show Comments
  20. Write a function called remove_dups that takes a string and creates a new string by only adding those characters that are not already present. In other words, there will never be a duplicate letter added to the new string.

    (ex_8_19)

  21. Write a function called rot13 that uses the Caesar cipher to encrypt a message. The Caesar cipher works like a substitution cipher but each character is replaced by the character 13 characters to ‘its right’ in the alphabet. So for example the letter a becomes the letter n. If a letter is past the middle of the alphabet then the counting wraps around to the letter a again, so n becomes a, o becomes b and so on. Hint: Whenever you talk about things wrapping around its a good idea to think of modulo arithmetic.

    (ex_8_20)

    18
     
    1
    def rot13(mess):
    2
        alphabet = 'abcdefghijklmnopqrstuvwxyz'
    3
        encrypted = ''
    4
        for char in mess:
    5
            if char == ' ':
    6
                encrypted = encrypted + ' '
    7
            else:
    8
                rotated_index = alphabet.index(char) + 13
    9
                if rotated_index < 26:
    10
                    encrypted = encrypted + alphabet[rotated_index]
    11
                else:
    12
                    encrypted = encrypted + alphabet[rotated_index % 26]
    13
        return encrypted
    14
    15
    print(rot13('abcde'))
    16
    print(rot13('nopqr'))
    17
    print(rot13(rot13('since rot thirteen is symmetric you should see this message')))
    18

    (str_q21_answer)

    Show Comments
  22. Modify this code so it prints each subtotal, the total cost, and average price to exactly two decimal places.

    (ex_8_22)

Next Section - 10. Lists