9.12. Exercises¶
What is the result of each of the following:
‘Python’[1]
“Strings are sequences of characters.”[5]
len(“wonderful”)
‘Mystery’[:4]
‘p’ in ‘Pineapple’
‘apple’ in ‘Pineapple’
‘pear’ not in ‘Pineapple’
‘apple’ > ‘pineapple’
‘pineapple’ < ‘Peach’
‘Python’[1] = ‘y’
‘Strings are sequences of characters.’[5] = ‘g’
len(‘wonderful’) = 9
‘Mystery’[:4] = ‘Myst’
‘p’ in ‘Pineapple’ = True
‘apple’ in ‘Pineapple’ = True
‘pear’ not in ‘Pineapple’ = True
‘apple’ > ‘pineapple’ = False
‘pineapple’ < ‘Peach’ = False
-
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)
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)
251def count(p):2lows = "abcdefghijklmnopqrstuvwxyz"3ups = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"45numberOfe = 06totalChars = 07for achar in p:8if achar in lows or achar in ups:9totalChars = totalChars + 110if achar == 'e':11numberOfe = numberOfe + 11213percent_with_e = (numberOfe / totalChars) * 10014print("Your text contains", totalChars, "alphabetic characters of which", numberOfe, "(", percent_with_e, "%)", "are 'e'.")151617p = '''18"If the automobile had followed the same development cycle as the computer, a19Rolls-Royce would today cost $100, get a million miles per gallon, and explode20once a year, killing everyone inside."21-Robert Cringely22'''2324count(p)25(str_q3_answer)
-
Print out a neatly formatted multiplication table, up to 12 x 12.
(ex_8_4)
Write a function that will return the number of digits in an integer.
(ex_7_10)
91def numDigits(n):2n_str = str(n)3return len(n_str)456print(numDigits(50))7print(numDigits(20000))8print(numDigits(1))9(str_q5_answer)
-
Write a function that reverses its string argument.
(ex_8_5)
Write a function that mirrors its string argument, generating a string containing the original string and the string backwards.
(ex_8_6)
161from test import testEqual23def reverse(mystr):4reversed = ''5for char in mystr:6reversed = char + reversed7return reversed89def mirror(mystr):10return mystr + reverse(mystr)1112testEqual(mirror('good'), 'gooddoog')13testEqual(mirror('Python'), 'PythonnohtyP')14testEqual(mirror(''), '')15testEqual(mirror('a'), 'aa')16(str_q7_answer)
-
Write a function that removes all occurrences of a given letter from a string.
(ex_8_7)
Write a function that recognizes palindromes. (Hint: use your
reversefunction to make this easy!).(ex_8_8)
201from test import testEqual23def reverse(mystr):4reversed = ''5for char in mystr:6reversed = char + reversed7return reversed89def is_palindrome(myStr):10if myStr in reverse(myStr):11return True12else:13return False1415testEqual(is_palindrome('abba'), True)16testEqual(is_palindrome('abab'), False)17testEqual(is_palindrome('straw warts'), True)18testEqual(is_palindrome('a'), True)19testEqual(is_palindrome(''), True)20(str_q9_answer)
Write a function that counts how many non-overlapping occurences of a substring appear in a string.
(ex_8_9)
Write a function that removes the first occurrence of a string from another string.
(ex_8_10)
141from test import testEqual23def remove(substr,theStr):4index = theStr.find(substr)5if index < 0: # substr doesn't exist in theStr6return theStr7return_str = theStr[:index] + theStr[index+len(substr):]8return return_str910testEqual(remove('an', 'banana'), 'bana')11testEqual(remove('cyc', 'bicycle'), 'bile')12testEqual(remove('iss', 'Mississippi'), 'Missippi')13testEqual(remove('egg', 'bicycle'), 'bicycle')14(str_q11_answer)
-
Write a function that removes all occurrences of a string from another string.
(ex_8_11)
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)
561import turtle23def createLSystem(numIters, axiom):4startString = axiom5endString = ""6for i in range(numIters):7endString = processString(startString)8startString = endString910return endString1112def processString(oldStr):13newstr = ""14for ch in oldStr:15newstr = newstr + applyRules(ch)1617return newstr1819def applyRules(ch):20newstr = ""21if ch == 'L':22newstr = '+RF-LFL-FR+' # Rule 123elif ch == 'R':24newstr = '-LF+RFR+FL-'25else:26newstr = ch # no rules apply so keep the character2728return newstr2930def drawLsystem(aTurtle, instructions, angle, distance):31for cmd in instructions:32if cmd == 'F':33aTurtle.forward(distance)34elif cmd == 'B':35aTurtle.backward(distance)36elif cmd == '+':37aTurtle.right(angle)38elif cmd == '-':39aTurtle.left(angle)4041def main():42inst = createLSystem(4, "L") # create the string43print(inst)44t = turtle.Turtle() # create the turtle45wn = turtle.Screen()4647t.up()48t.back(200)49t.down()50t.speed(9)51drawLsystem(t, inst, 90, 5) # draw the picture52# angle 90, segment length 553wn.exitonclick()5455main()56(str_q13_answer)
-
Here is a dragon curve. Use 90 degrees.:
FX X -> X+YF+ Y -> -FX-Y
(ex_8_13)
Here is something called an arrowhead curve. Use 60 degrees.:
YF X -> YF+XF+Y Y -> XF-YF-X
(ex_8_14)
531import turtle23def createLSystem(numIters, axiom):4startString = axiom5endString = ""6for i in range(numIters):7endString = processString(startString)8startString = endString910return endString1112def processString(oldStr):13newstr = ""14for ch in oldStr:15newstr = newstr + applyRules(ch)1617return newstr1819def applyRules(ch):20newstr = ""21if ch == 'X':22newstr = 'YF+XF+Y' # Rule 123elif ch == 'Y':24newstr = 'XF-YF-X'25else:26newstr = ch # no rules apply so keep the character2728return newstr2930def drawLsystem(aTurtle, instructions, angle, distance):31for cmd in instructions:32if cmd == 'F':33aTurtle.forward(distance)34elif cmd == 'B':35aTurtle.backward(distance)36elif cmd == '+':37aTurtle.right(angle)38elif cmd == '-':39aTurtle.left(angle)4041def main():42inst = createLSystem(5, "YF") # create the string43print(inst)44t = turtle.Turtle() # create the turtle45wn = turtle.Screen()4647t.speed(9)48drawLsystem(t, inst, 60, 5) # draw the picture49# angle 90, segment length 550wn.exitonclick()5152main()53(str_q15_answer)
-
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)
The Sierpinski Triangle. Use 60 degrees.:
FXF--FF--FF F -> FF X -> --FXF++FXF++FXF--
(ex_8_16)
591import turtle23def createLSystem(numIters, axiom):4startString = axiom5endString = ""6for i in range(numIters):7endString = processString(startString)8startString = endString910return endString1112def processString(oldStr):13newstr = ""14for ch in oldStr:15newstr = newstr + applyRules(ch)1617return newstr1819def applyRules(ch):20newstr = ""21if ch == 'F':22newstr = 'FF' # Rule 123elif ch == 'X':24newstr = '--FXF++FXF++FXF--'25else:26newstr = ch # no rules apply so keep the character2728return newstr2930def drawLsystem(aTurtle, instructions, angle, distance):31for cmd in instructions:32if cmd == 'F':33aTurtle.forward(distance)34elif cmd == 'B':35aTurtle.backward(distance)36elif cmd == '+':37aTurtle.right(angle)38elif cmd == '-':39aTurtle.left(angle)4041def main():42inst = createLSystem(5, "FXF--FF--FF") # create the string43print(inst)44t = turtle.Turtle() # create the turtle45wn = turtle.Screen()46t.up()47t.back(200)48t.right(90)49t.forward(100)50t.left(90)51t.down()52t.speed(9)5354drawLsystem(t, inst, 60, 5) # draw the picture55# angle 90, segment length 556wn.exitonclick()5758main()59(str_q17_answer)
-
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)
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)
311def encrypt(message, cipher):2alphabet = "abcdefghijklmnopqrstuvwxyz"3encrypted = ''4for char in message:5if char == ' ':6encrypted = encrypted + ' '7else:8pos = alphabet.index(char)9encrypted = encrypted + cipher[pos]10return encrypted1112def decrypt(encrypted, cipher):13alphabet = "abcdefghijklmnopqrstuvwxyz"14decrypted = ''15for char in encrypted:16if char == ' ':17decrypted = decrypted + ' '18else:19pos = cipher.index(char)20decrypted = decrypted + alphabet[pos]21return decrypted222324cipher = "badcfehgjilknmporqtsvuxwzy"2526encrypted = encrypt('hello world', cipher)27print encrypted2829decrypted = decrypt(encrypted, cipher)30print(decrypted)31(str_q19_answer)
-
Write a function called
remove_dupsthat 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)
Write a function called
rot13that 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)
181def rot13(mess):2alphabet = 'abcdefghijklmnopqrstuvwxyz'3encrypted = ''4for char in mess:5if char == ' ':6encrypted = encrypted + ' '7else:8rotated_index = alphabet.index(char) + 139if rotated_index < 26:10encrypted = encrypted + alphabet[rotated_index]11else:12encrypted = encrypted + alphabet[rotated_index % 26]13return encrypted1415print(rot13('abcde'))16print(rot13('nopqr'))17print(rot13(rot13('since rot thirteen is symmetric you should see this message')))18(str_q21_answer)
-
Modify this code so it prints each subtotal, the total cost, and average price to exactly two decimal places.
(ex_8_22)