Skip to content

Latest commit

 

History

History
148 lines (99 loc) · 2 KB

File metadata and controls

148 lines (99 loc) · 2 KB

Collections

id([1,2]) # address of object in memory
from collections import namedtuple

Person = namedtuple("Person", ['name', 'age'])
p = Person("George", age =77)
p._fields
# ('name', 'age')

p.name, p.age
# ("George", 77)

p._asdict()
# {'name': 'George', 'age': 77}

p._replace(name="Bill")

WRONG!

chunks = [[0]] * 2
print(chunks) # [[0], [0]]

chunks[0][0] = 42

print(chunks) # [[42], [42]]

RIGHT!

chunks = [[0] for _ in range(2)]
print(chunks) # [[0], [0]]

chunks[0][0] = 42

print(chunks) # [[42], [0]]
xs = [1, 2, 3]
xs[:2] = [0] * 2

xs # [0, 0, 3]

Deque !!!!

deque.popleft, and deque.pop == O(1) ( list.pop(0) == O(n) )
indexing == O(n)

from collections import deque

q = deque([1,2,3])
q.appendleft(0)
q.append(4)
print(q)    # deque([0, 1, 2, 3, 4])

q.popleft()
q.pop()
print(q)    # deque([1, 2, 3])

# ==== MAX LEN ================ 

q = deque([0,1], maxlen=2)
q.append(2)

print(q) #  deque([1, 2], maxlen=2)
a, b, c = {1, 2}, {2, 3}, {3, 4}

a.isdisjoint(b)

print(a <= b)       # a ⊆ b == False

print(a < a)       # a ⊂ a == False

print(a | b >= c)   # a ∪ b ⊇ c == False

Frozenset

set()

frozenset()

Dict

dict(
    name="ALex", age=77
) # {'name': 'ALex', 'age': 77}

dict.fromkeys(['name', 'age'])
# {'name': None, 'age': None}

dict.fromkeys('abcdef', 0)
# {'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0, 'f': 0}

{}.get("any", 0)
# 0

p = {'b': 1, 'c': 2}
# if value 'a' not set, setting it 123
# otherwise ignore
p.setdefault('a', 123)  # 123
# returns value of a, if new - new
p.setdefault('b', 123)  # 1

print(p)
# {'a': 123, 'b': 1, 'c': 2}
from collections import Counter

c = Counter(['foo', 'foo', 'foo', 'bar'])
print(c)
# Counter({'foo': 3, 'bar': 1})

print(c['foo'])
# 3

c.update(['foo'])

c = Counter(foo=10, bar=-1)
print(c)
# Counter({'foo': 10, 'bar': -1})

c.subtract({'foo': 100})

print(c)
# Counter({'bar': -1, 'foo': -90})