Skip to main content

Exercises 9.22 Exercises

  1. 1.

    Solution.
    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
  2. 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?
  3. 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'.
    
    Solution.
    def count(p):
        lows = "abcdefghijklmnopqrstuvwxyz"
        ups =  "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    
        numberOfe = 0
        totalChars = 0
        for achar in p:
            if achar in lows or achar in ups:
                totalChars = totalChars + 1
                if achar == 'e':
                    numberOfe = numberOfe + 1
    
        percent_with_e = (numberOfe / totalChars) * 100
        print("Your text contains", totalChars, "alphabetic characters of which", numberOfe, "(", percent_with_e, "%)", "are 'e'.")
    
    
    p = '''
    "If the automobile had followed the same development cycle as the computer, a
    Rolls-Royce would today cost $100, get a million miles per gallon, and explode
    once a year, killing everyone inside."
    -Robert Cringely
    '''
    
    count(p)
    
  4. 4.

    Print out a neatly formatted multiplication table, up to 12 x 12.
  5. 5.

    Write a function that will return the number of digits in an integer.
    Solution.
    def numDigits(n):
        n_str = str(n)
        return len(n_str)
    
    
    print(numDigits(50))
    print(numDigits(20000))
    print(numDigits(1))
    
  6. 6.

    Write a function that reverses its string argument.
  7. 7.

    Solution.
    from test import testEqual
    
    def reverse(mystr):
        reversed = ''
        for char in mystr:
            reversed = char + reversed
        return reversed
    
    def mirror(mystr):
        return mystr + reverse(mystr)
    
    testEqual(mirror('good'), 'gooddoog')
    testEqual(mirror('Python'), 'PythonnohtyP')
    testEqual(mirror(''), '')
    testEqual(mirror('a'), 'aa')
    
  8. 8.

    Write a function that removes all occurrences of a given letter from a string.
  9. 9.

    Write a function that recognizes palindromes. (Hint: use your reverse function to make this easy!).
    Solution.
    from test import testEqual
    
    def reverse(mystr):
        reversed = ''
        for char in mystr:
            reversed = char + reversed
        return reversed
    
    def is_palindrome(myStr):
        if myStr in reverse(myStr):
            return True
        else:
            return False
    
    testEqual(is_palindrome('abba'), True)
    testEqual(is_palindrome('abab'), False)
    testEqual(is_palindrome('straw warts'), True)
    testEqual(is_palindrome('a'), True)
    testEqual(is_palindrome(''), True)
    
  10. Write a function that counts how many non-overlapping occurences of a substring appear in a string.
  11. 10.

    Write a function that removes the first occurrence of a string from another string.
    Solution.
    from test import testEqual
    
    def remove(substr,theStr):
        index = theStr.find(substr)
        if index < 0: # substr doesn't exist in theStr
            return theStr
        return_str = theStr[:index] + theStr[index+len(substr):]
        return return_str
    
    testEqual(remove('an', 'banana'), 'bana')
    testEqual(remove('cyc', 'bicycle'), 'bile')
    testEqual(remove('iss', 'Mississippi'), 'Missippi')
    testEqual(remove('egg', 'bicycle'), 'bicycle')
    
  12. 11.

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

    Here is another interesting L-System called a Hilbert curve. Use 90 degrees:
    L
    L -> +RF-LFL-FR+
    R -> -LF+RFR+FL-
    
    Solution.
    import turtle
    
    def createLSystem(numIters, axiom):
        startString = axiom
        endString = ""
        for i in range(numIters):
            endString = processString(startString)
            startString = endString
    
        return endString
    
    def processString(oldStr):
        newstr = ""
        for ch in oldStr:
            newstr = newstr + applyRules(ch)
    
        return newstr
    
    def applyRules(ch):
        newstr = ""
        if ch == 'L':
            newstr = '+RF-LFL-FR+'   # Rule 1
        elif ch == 'R':
            newstr = '-LF+RFR+FL-'
        else:
            newstr = ch     # no rules apply so keep the character
    
        return newstr
    
    def drawLsystem(aTurtle, instructions, angle, distance):
        for cmd in instructions:
            if cmd == 'F':
                aTurtle.forward(distance)
            elif cmd == 'B':
                aTurtle.backward(distance)
            elif cmd == '+':
                aTurtle.right(angle)
            elif cmd == '-':
                aTurtle.left(angle)
    
    def main():
        inst = createLSystem(4, "L")  # create the string
        print(inst)
        t = turtle.Turtle()           # create the turtle
        wn = turtle.Screen()
    
        t.up()
        t.back(200)
        t.down()
        t.speed(9)
        drawLsystem(t, inst, 90, 5)   # draw the picture
                                      # angle 90, segment length 5
        wn.exitonclick()
    
    main()
    
  14. 13.

    Here is a dragon curve. Use 90 degrees.:
    FX
    X -> X+YF+
    Y -> -FX-Y
    
  15. 14.

    Here is something called an arrowhead curve. Use 60 degrees.:
    YF
    X -> YF+XF+Y
    Y -> XF-YF-X
    
    Solution.
    import turtle
    
    def createLSystem(numIters, axiom):
        startString = axiom
        endString = ""
        for i in range(numIters):
            endString = processString(startString)
            startString = endString
    
        return endString
    
    def processString(oldStr):
        newstr = ""
        for ch in oldStr:
            newstr = newstr + applyRules(ch)
    
        return newstr
    
    def applyRules(ch):
        newstr = ""
        if ch == 'X':
            newstr = 'YF+XF+Y'   # Rule 1
        elif ch == 'Y':
            newstr = 'XF-YF-X'
        else:
            newstr = ch     # no rules apply so keep the character
    
        return newstr
    
    def drawLsystem(aTurtle, instructions, angle, distance):
        for cmd in instructions:
            if cmd == 'F':
                aTurtle.forward(distance)
            elif cmd == 'B':
                aTurtle.backward(distance)
            elif cmd == '+':
                aTurtle.right(angle)
            elif cmd == '-':
                aTurtle.left(angle)
    
    def main():
        inst = createLSystem(5, "YF")  # create the string
        print(inst)
        t = turtle.Turtle()            # create the turtle
        wn = turtle.Screen()
    
        t.speed(9)
        drawLsystem(t, inst, 60, 5)    # draw the picture
                                       # angle 90, segment length 5
        wn.exitonclick()
    
    main()
    
  16. 15.

    Try the Peano-Gosper curve. Use 60 degrees.:
    FX
    X -> X+YF++YF-FX--FXFX-YF+
    Y -> -FX+YFYF++YF+FX--FX-Y
    
  17. 16.

    The Sierpinski Triangle. Use 60 degrees.:
    FXF--FF--FF
    F -> FF
    X -> --FXF++FXF++FXF--
    
    Solution.
    import turtle
    
    def createLSystem(numIters, axiom):
        startString = axiom
        endString = ""
        for i in range(numIters):
            endString = processString(startString)
            startString = endString
    
        return endString
    
    def processString(oldStr):
        newstr = ""
        for ch in oldStr:
            newstr = newstr + applyRules(ch)
    
        return newstr
    
    def applyRules(ch):
        newstr = ""
        if ch == 'F':
            newstr = 'FF'   # Rule 1
        elif ch == 'X':
            newstr = '--FXF++FXF++FXF--'
        else:
            newstr = ch     # no rules apply so keep the character
    
        return newstr
    
    def drawLsystem(aTurtle, instructions, angle, distance):
        for cmd in instructions:
            if cmd == 'F':
                aTurtle.forward(distance)
            elif cmd == 'B':
                aTurtle.backward(distance)
            elif cmd == '+':
                aTurtle.right(angle)
            elif cmd == '-':
                aTurtle.left(angle)
    
    def main():
        inst = createLSystem(5, "FXF--FF--FF")   # create the string
        print(inst)
        t = turtle.Turtle()           # create the turtle
        wn = turtle.Screen()
        t.up()
        t.back(200)
        t.right(90)
        t.forward(100)
        t.left(90)
        t.down()
        t.speed(9)
    
        drawLsystem(t, inst, 60, 5)   # draw the picture
                                      # angle 90, segment length 5
        wn.exitonclick()
    
    main()
    
  18. 17.

    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.
  19. 18.

    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.
    Solution.
    def encrypt(message, cipher):
        alphabet = "abcdefghijklmnopqrstuvwxyz"
        encrypted = ''
        for char in message:
            if char == ' ':
                encrypted = encrypted + ' '
            else:
                pos = alphabet.index(char)
                encrypted = encrypted + cipher[pos]
        return encrypted
    
    def decrypt(encrypted, cipher):
        alphabet = "abcdefghijklmnopqrstuvwxyz"
        decrypted = ''
        for char in encrypted:
            if char == ' ':
                decrypted = decrypted + ' '
            else:
                pos = cipher.index(char)
                decrypted = decrypted + alphabet[pos]
        return decrypted
    
    
    cipher = "badcfehgjilknmporqtsvuxwzy"
    
    encrypted = encrypt('hello world', cipher)
    print encrypted
    
    decrypted = decrypt(encrypted, cipher)
    print(decrypted)
    
  20. 19.

    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.
  21. 20.

    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.
    Solution.
    def rot13(mess):
        alphabet = 'abcdefghijklmnopqrstuvwxyz'
        encrypted = ''
        for char in mess:
            if char == ' ':
                encrypted = encrypted + ' '
            else:
                rotated_index = alphabet.index(char) + 13
                if rotated_index < 26:
                    encrypted = encrypted + alphabet[rotated_index]
                else:
                    encrypted = encrypted + alphabet[rotated_index % 26]
        return encrypted
    
    print(rot13('abcde'))
    print(rot13('nopqr'))
    print(rot13(rot13('since rot thirteen is symmetric you should see this message')))
    
  22. 21.

    Modify this code so it prints each subtotal, the total cost, and average price to exactly two decimal places.
You have attempted of activities on this page.