Previously on Prog 2¶
Types¶
- None Type
- Union Types
Union[str, int]
- Optional
Optional[str]
- Syntax with
|
str | int
- Tuples
Tuple[int, str]
Exceptions¶
if dimensions(a) != dimensions(b):
raise ValueError("Matrices should have the same dimensions")
Assignment vs Copy¶
In [23]:
a = [1,2,3]
b = a
b[2] = 100
a[0] = 12
a =
print("a =", a)
print("b =", b)
a = [1, 2] b = [12, 2, 100]
In [24]:
a = [1,2,3]
b = a.copy()
b[2] = 100
print("a =", a)
print("b =", b)
a = [1, 2, 3] b = [1, 2, 100]
Assignment vs Copy
Simple Copy (Shallow) vs Deep Copy
Shallow Copy
In [25]:
a = [[1, 2, 3], [4, 5, 6]]
b = a.copy()
b[0] = [7, 8, 9]
print("a =", a)
print("b =", b)
a = [[1, 2, 3], [4, 5, 6]] b = [[7, 8, 9], [4, 5, 6]]
In [26]:
a = [[1, 2, 3], [4, 5, 6]]
b = a.copy()
b[0][1] = 100
print("a =", a)
print("b =", b)
a = [[1, 100, 3], [4, 5, 6]] b = [[1, 100, 3], [4, 5, 6]]
Simple Copy (Shallow) vs Deep Copy
Deep Copy
In [28]:
import copy
a = [[1, 2, 3], [4, 5, 6]]
b = copy.deepcopy(a)
b[0][1] = 100
print("a =", a)
print("b =", b)
a = [[1, 2, 3], [4, 5, 6]] b = [[1, 100, 3], [4, 5, 6]]
In [30]:
ages = {
"Peter" : 10,
"Alice" : 10,
"Bob" : 25
}
ages["Alice"]
Out[30]:
10
In [ ]:
fruits = {
"Bananas" : (105, 3.25),
"Apples" : (150, 2.75),
"Strawberries" : (0, 4.75)
}
Dictionary Operations - Part1
- Length of a Dictionary :
len mydict
- Get a value:
mydict[key]
ormydict.get(key)
- Check if a key exists
key in mydict
- Change a value:
mydict[key] = new_value
- List of keys:
mydict.keys()
- List of values:
mydict.values()
- List of items (key, value) :
mydict.items()
Dictionary operations - Simple methods
In [44]:
fruits = {
"banana" : (105, 3.25),
"apple" : (150, 2.75),
"orange" : (0, 4.75),
"pear" : (15, 1.5)
}
fruits.values()
Out[44]:
dict_values([(105, 3.25), (150, 2.75), (0, 4.75), (15, 1.5)])
Dictionary operations - Iteration
In [45]:
fruits = {
"banana" : (105, 3.25),
"apple" : (150, 2.75),
"orange" : (0, 4.75),
"pear" : (15, 1.5)
}
value = 0
for n, p in fruits.values():
value += n * p
value
Out[45]:
776.25
Dictionary - Exercise: Shopping List
In [60]:
from typing import Tuple, Dict
def bill(prices: Dict[str, float], shopping_list: List[Tuple[str, int]]) -> float:
total = 0.0
for item, n in shopping_list:
price = prices.get(item)
if not price:
print(f"{item} out of stock")
else:
total += price * n
return total
In [63]:
my_prices = { "banana" : 1.25, "apple" : 2.75, "orange" : 3.75, "pear" : 1.5 }
#bill(my_prices, ["banana", "pear", "bananax"])
bill(my_prices, [("banana", 24), ("pear", 1)])
Out[63]:
31.5
Dictionary - Exercise: Word Count
In [ ]:
def word_count(text: str) -> Dict[str, int]:
words = text.split()
counts: Dict[str, int] = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
return counts
wc = word_count("aa bbb aa ccc bbb aa zz aa")
for word, count in wc.items():
print(f'{word:10} {count}')
Nested Dictionaries
In [64]:
fruits = {
"banana" : {
"stock": 105,
"price" : 3.25
},
"apple" : {
"stock" : 150,
"price" : 2.75
}
}
fruits["banana"]["price"]
dict[str, Any]
Out[64]:
3.25
Dictionary Comprehension¶
In [66]:
# Squares of natural numbers
squares = {x : x*x for x in range(11)}
print(squares)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
In [70]:
# conditions in comprehensions
{ x: x*x for x in range(12) if x%3 != 0}
Out[70]:
{1: 1, 2: 4, 4: 16, 5: 25, 7: 49, 8: 64, 10: 100, 11: 121}
Sets
A collection of non duplicate items
For example¶
In [75]:
people = {"John", "Rick", "Ed", "Jose", "Ed"}
print(people)
{'John', 'Jose', 'Ed', 'Rick'}
Adding and removing elements¶
In [76]:
people.add("Ed")
people.remove("Rick")
print(people)
{'John', 'Jose', 'Ed'}
Check existence¶
In [77]:
"Maria" in people
Out[77]:
False
Beware of the Empty Set
In [79]:
a = {}
a["xxx"] = 10
a
Out[79]:
{'xxx': 10}
In [ ]:
a = set()
a.add("xxx")
a
Operation between Sets
Operation between Sets
In [80]:
people2 = {"Maria", "Ed", "Jose"}
print(people)
print(people2)
{'John', 'Jose', 'Ed'} {'Maria', 'Jose', 'Ed'}
In [81]:
people.union(people2)
people | people2
Out[81]:
{'Ed', 'John', 'Jose', 'Maria'}
In [82]:
people.intersection(people2)
people & people2
Out[82]:
{'Ed', 'Jose'}
In [83]:
people.difference(people2)
print(people - people2)
print(people2 - people)
{'John'} {'Maria'}
In [84]:
people.symmetric_difference(people2)
people ^ people2
Out[84]:
{'John', 'Maria'}
Other Functions
- all, any
- enumerate
- len, max, min, sum
- isdisjoint, issubset, issuperset
In [87]:
a = {True, False, True}
sum({100, 10, 500})
Out[87]:
610
Frozen (Inmutable) Sets
You can create a set using
frozenset
so elements cannot be changed after construction
In [91]:
A = frozenset({1, 2, 3, 4})
B = frozenset({3, 4})
A.issuperset(B)
a | B
Out[91]:
{False, True, 3, 4}
In [ ]:
A.add(100)