CS 111: Program Design I Lecture 5: Strings (cont.) & heading to Caesar Robert H. Sloan & Richard Warner
University of Illinois at Chicago September 6, 2016
Alternate Problem if not taking survey: Evaluate in your head; check with computer when done: 1. 5 ** 2 2. 9 * 5 3. 15 / 12 4. 12 / 15 5. 15 // 12 6. 12 // 15 7. 5 % 2 8. 9 % 5
9. 15 % 12 10. 12 % 15 11. 6 % 6 12. 0 % 7
Review: print() function, types
n At the end of this code right below:
print(3*5)print("3*5")what will have been printed?
A.3*53*5B.1515C.15 D. 3*53*5 15
Review: Indexing (including negative)
>>>s="Registertovote!">>>len(s)
17>>>s[7]'r'>>>s[17]error!>>>s[len(s)-1]'!'>>>s[-1]'!'
012345678911111110123456
Review of find: This will print?
hi="HelloWorld"hey="Heyworld!"print(hi.find('o'),hey.find('o'))A. 44B. 45C. 55D. 56
find() String method works for substrings too hi="HelloWorld"hey="Heyworld!"print(hi.find('ello'),hey.find('ello'))A. 2-1B. 1-1C. 11D. 22E. Error
Slicing: Getting part of a string
n Substring of a string is called slice n s[m:n] returns characters from index m
(counting from 0 as always) up to but not including character n
cj="ChiefJusticeRoberts"
012345678901234567890
cj[0:5]à'Chief'cj[6:10]à'Just'
Slicing: omission = start/end
cj="ChiefJusticeRoberts"012345678901234567890
cj[:13]à'ChiefJustice'cj[14:]à'Roberts'and sort of silly one: cj[:]à'ChiefJusticeRoberts'
Another slice example
>>>s="Registertovote!">>>s[9:11]'to'>>>s[12:20]error!
012345678911111110123456
Slice can also use negative indices
>>>s="Registertovote!">>>s[len(s)-1]'!'>>>s[-1]'!'>>>s[1:-1]'egistertovote'
012345678911111110123456
Fancy slicing you'll never use
n You are allowed to give 3 indices, which are interpreted as start:end:step
cj="ChiefJusticeRoberts"012345678901234567890
cj[4:17:3]
Fancy slicing you'll never use
n You are allowed to give 3 indices, which are interpreted as start:end:step
cj="ChiefJusticeRoberts"012345678901234567890
cj[4:17:3]à'fuib'
Fancy slicing you'll never use except for this one trick for Homework 2 n A weird way to reverse a string s (when we
haven't yet talked about loops) is s[::-1] q Give me the whole string, stepping 1 backwards
each time!
n >>> firstChief[::-1] n 'yaJ'
Some people objects just never change
n In Python, integers are immutable q Cannot assign to integer object q I.e., cannot write 1 = 0
n Probably not a surprise
n Important: strings are immutable too! firstJustice="Jay"firstJustice[0]="H"Illegal;ERROR!
But Professor
n Can write n=1n=0n Is that changing an integer? n NO! Changing which object variable name n
is assigned to n Could reassign (entire object of) firstJusticetoo
Pictures
0
'Jay'
Some immutable objects in object space (memory)
n firstJustice
n = 0 doesn't change immutable integer 1, just the assignment of a variable to an object
Pictures
0
'Jay'
Some immutable objects in object space (memory)
n firstJustice
firstJustice = 0 doesn't change immutable string 'Jay', just the assignment of variable to an object
Problem with firstJustice[0] = "H" after firstJustice = "Jay"
'Jay'
Some immutable objects in object space (memory)
firstJustice
firstJutice[0] = "H" is illegal because we cannot change the contents of any of the yellow boxes. Those objects are immutable
Coming attractions: Mutable types
n Numbers, Booleans, and strings are all immutable
n Python does have some mutable types q Two very important ones we will see are q Lists and dictionaries
At the heart of the cipher is shifting letters n Every letter is shifted k to left or right in
alphabet, where combination of k and left or right is encryption key
n First design decision: Encode key (have inputs to shift function) as q 2 inputs: positive integer and "left" or "right q 1 input, integer, with sign indicating left/right
n And if 1 input, is negative shift left or right
At the heart of the cipher is shifting letters n Every letter is shifted k to left or right in
alphabet, where combination of k and left or right is encryption key
n First design decision: Encode key (have inputs to shift function) as q 2 inputs: positive integer and "left" or "right q 1 input, integer, with sign indicating left/right
n And if 1 input, is negative shift left or right q All possible answers seem reasonable; so pick
one and see how it works
At the heart of the cipher is shifting letters n Every letter is shifted k to left or right in
alphabet, where combination of k and left or right is encryption key
n First design decision: Encode key (have inputs to shift function) as q 2 inputs: positive integer and "left" or "right q 1 input, integer, with sign indicating left/right
n And if 1 input, is negative shift left or right q Our arbitrary answer: + = shift right/up in alphabet:
n + 3 means shift A to C
Example: +3 Shift
ABCDEFGHIJKLMNOPQRSTUVWXYZà+3SHIFTDEFGHIJKLMNOPQRSTUVWXYZ???What do we do when we run off the end?
Wrap around! ABCDEFGHIJKLMNOPQRSTUVWXYZà+3SHIFTDEFGHIJKLMNOPQRSTUVWXYZABC
How do we implement k shift?
n We need letter number i transformed to letter i + k, assuming i + k is not past z, and to wrap otherwise
n How do we find what letter a given character is in the alphabet?
A. find B. Indexing C. String addition D. Using the remainder function %
Finding letter in alphabet
ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'>>>ALPHABET.find('A')A. 0B. 1C. ErrorD. Non-errorotherthan0or1
find() gives position in alphabet
n Using Python 0 to 25 numbering! n And adding k to go forward just works
q if we don't fall off the end n Trick you will repeatedly as a computer
scientist: remainder (also called mod) operator % works for "wrapping around"
n E.g., Z forward 3 should give C n (25 + 3) % 26 à 2
q Recall ALPHABET[25] à Z
% for rotating, wrapping around
n Wikipedia and others describer Caesar cipher as using shift of letters
n Computer scientists often speak of rotation n In your head, think of 26 letters of alphabet in
a circle not in a line
You have the pieces of shift_letter
defshift_letter(character,k):'''Returnsashiftofcharacterkpositionsrightfork>0,wrappingaroundifpastz'''ALPHABET="ABCDEFGHIJKLMNOPQRSTUVWXYZ"position=ALPHABET.find(character)returnALPHABET[(position+k)%len(ALPHABET)]
But we need some more Python
n How do we q Handle left shifts
n Julius Caesar used a shift left of 3 n And need opposite direction shift to decrypt
q Encrypt a whole string, such as "ATTACK" or "RETREAT" instead of just 1 character
q Handle mixed case and spaces, as in "ATTACK AT DAWN"
Types: Booleans
>>>2+2==4True>>>'cat'=='cat'True>>>2==4False>>>2!=4True
Note operator is == (two = symbols)
String Boolean Operators
2 symmetric arguments: == equals != is not equal to 2 arguments; order matters: in tells if lhs is substring of rhs
e.g., "c" in "cat" à true
Unary operator: not negates (flips True/False)
Just FYI: Later in the semester
Also > greater than >= greater than or equal to < less than <= less than or equal to
Which of the following will evaluate to True after first line? x="ATTACKATDAWN"A. "AT"==xB. "AT"inxC. x==6D. x!=3E. Morethanoneoftheabove