dictionaries, sets, and comprehension intro2cs – week 4 part ii 1
DESCRIPTION
Other Complex Data Types in Python Dictionary Set 3 ages = {“dov”:12, “shir”:13} rooms = {212, 215, 367}TRANSCRIPT
1
Dictionaries, Sets, and Comprehension
Intro2CS – week 4 part II
2
Complex Data Types you have seen
StringList
RangeTuple
3
Other Complex Data Types in Python
• Dictionary
• Set
ages = {“dov”:12, “shir”:13}
rooms = {212, 215, 367}
4
Dictionaries
5
Phone book application
Accepts a sequence of commands of the following possible forms:– store name number: add this contact to the phone
book– phone name: print the number for this name– exit: exit
6
Phone Book
7
Sets
8
Unique Elements
9
MutabilityType Mutable?
String No
Tuple No
List Yes
Dictionary Yes
Set Yes
Frozenset No
Bool, Int, Float No
Rule: Elements in sets and keys in dictionaries must be immutable
10
List Comprehension
Mathematical notation: S = { x2 | x = 1…N}
Python Notation:
11
List comprehension implementation
l = [exp(i) for i in seq if cond(i)]
l = []for i in seq: if cond(i): l.append(exp(i))
12
Factors
Perfect Numbers: [6, 28, 496, 8128]Prime numbers: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
13
Dictionary and Set comprehension
14
Substitution CodesSubstitution codes:
abcdefghijklmnopqrstuvwxyzqwertyuiopasdfghjklzxcvbnm
hello itssg
Ceaser’s original code: shift by 3abcdefghijklmnopqrstuvwxyzxyzabcdefghijklmnopqrstuvw
Rot13: shift by 13
15
Our implementation
• A code is a dictionary: letter letter
• ceaser_code(shift) code
• Encrypt(plaintext, code) ciphertext
• Decrypt(ciphertext, code) plaintext
16
Ceaser Code
jul qvq gur puvpxra pebff gur ebnq? ==> why did the chicken cross the road?