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"
4
5numberOfe = 0
6totalChars = 0
7for achar in p:
8if achar in lows or achar in ups:
9totalChars = totalChars + 1
10if achar == 'e':
11numberOfe = numberOfe + 1
12
13percent_with_e = (numberOfe / totalChars) * 100
14print("Your text contains", totalChars, "alphabetic characters of which", numberOfe, "(", percent_with_e, "%)", "are 'e'.")
15
16
17p = '''
18"If the automobile had followed the same development cycle as the computer, a
19Rolls-Royce would today cost $100, get a million miles per gallon, and explode
20once a year, killing everyone inside."
21-Robert Cringely
22'''
23
24count(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)
4
5
6print(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 testEqual
2
3def reverse(mystr):
4reversed = ''
5for char in mystr:
6reversed = char + reversed
7return reversed
8
9def mirror(mystr):
10return mystr + reverse(mystr)
11
12testEqual(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
reverse
function to make this easy!).(ex_8_8)
201from test import testEqual
2
3def reverse(mystr):
4reversed = ''
5for char in mystr:
6reversed = char + reversed
7return reversed
8
9def is_palindrome(myStr):
10if myStr in reverse(myStr):
11return True
12else:
13return False
14
15testEqual(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 testEqual
2
3def remove(substr,theStr):
4index = theStr.find(substr)
5if index < 0: # substr doesn't exist in theStr
6return theStr
7return_str = theStr[:index] + theStr[index+len(substr):]
8return return_str
9
10testEqual(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 turtle
2
3def createLSystem(numIters, axiom):
4startString = axiom
5endString = ""
6for i in range(numIters):
7endString = processString(startString)
8startString = endString
9
10return endString
11
12def processString(oldStr):
13newstr = ""
14for ch in oldStr:
15newstr = newstr + applyRules(ch)
16
17return newstr
18
19def applyRules(ch):
20newstr = ""
21if ch == 'L':
22newstr = '+RF-LFL-FR+' # Rule 1
23elif ch == 'R':
24newstr = '-LF+RFR+FL-'
25else:
26newstr = ch # no rules apply so keep the character
27
28return newstr
29
30def 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)
40
41def main():
42inst = createLSystem(4, "L") # create the string
43print(inst)
44t = turtle.Turtle() # create the turtle
45wn = turtle.Screen()
46
47t.up()
48t.back(200)
49t.down()
50t.speed(9)
51drawLsystem(t, inst, 90, 5) # draw the picture
52# angle 90, segment length 5
53wn.exitonclick()
54
55main()
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 turtle
2
3def createLSystem(numIters, axiom):
4startString = axiom
5endString = ""
6for i in range(numIters):
7endString = processString(startString)
8startString = endString
9
10return endString
11
12def processString(oldStr):
13newstr = ""
14for ch in oldStr:
15newstr = newstr + applyRules(ch)
16
17return newstr
18
19def applyRules(ch):
20newstr = ""
21if ch == 'X':
22newstr = 'YF+XF+Y' # Rule 1
23elif ch == 'Y':
24newstr = 'XF-YF-X'
25else:
26newstr = ch # no rules apply so keep the character
27
28return newstr
29
30def 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)
40
41def main():
42inst = createLSystem(5, "YF") # create the string
43print(inst)
44t = turtle.Turtle() # create the turtle
45wn = turtle.Screen()
46
47t.speed(9)
48drawLsystem(t, inst, 60, 5) # draw the picture
49# angle 90, segment length 5
50wn.exitonclick()
51
52main()
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 turtle
2
3def createLSystem(numIters, axiom):
4startString = axiom
5endString = ""
6for i in range(numIters):
7endString = processString(startString)
8startString = endString
9
10return endString
11
12def processString(oldStr):
13newstr = ""
14for ch in oldStr:
15newstr = newstr + applyRules(ch)
16
17return newstr
18
19def applyRules(ch):
20newstr = ""
21if ch == 'F':
22newstr = 'FF' # Rule 1
23elif ch == 'X':
24newstr = '--FXF++FXF++FXF--'
25else:
26newstr = ch # no rules apply so keep the character
27
28return newstr
29
30def 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)
40
41def main():
42inst = createLSystem(5, "FXF--FF--FF") # create the string
43print(inst)
44t = turtle.Turtle() # create the turtle
45wn = turtle.Screen()
46t.up()
47t.back(200)
48t.right(90)
49t.forward(100)
50t.left(90)
51t.down()
52t.speed(9)
53
54drawLsystem(t, inst, 60, 5) # draw the picture
55# angle 90, segment length 5
56wn.exitonclick()
57
58main()
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 encrypted
11
12def decrypt(encrypted, cipher):
13alphabet = "abcdefghijklmnopqrstuvwxyz"
14decrypted = ''
15for char in encrypted:
16if char == ' ':
17decrypted = decrypted + ' '
18else:
19pos = cipher.index(char)
20decrypted = decrypted + alphabet[pos]
21return decrypted
22
23
24cipher = "badcfehgjilknmporqtsvuxwzy"
25
26encrypted = encrypt('hello world', cipher)
27print encrypted
28
29decrypted = decrypt(encrypted, cipher)
30print(decrypted)
31
(str_q19_answer)
-
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)
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)
181def rot13(mess):
2alphabet = 'abcdefghijklmnopqrstuvwxyz'
3encrypted = ''
4for char in mess:
5if char == ' ':
6encrypted = encrypted + ' '
7else:
8rotated_index = alphabet.index(char) + 13
9if rotated_index < 26:
10encrypted = encrypted + alphabet[rotated_index]
11else:
12encrypted = encrypted + alphabet[rotated_index % 26]
13return encrypted
14
15print(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)