Python Reference
Abstract
Minimal Python reference I found useful to solve random LeetCode questions.
This reference is purposely limited to these problems.
# Integer division and modulo
32 // 10 # 3
32 % 10 # 2
divmod(32, 10) # (3, 2)
divmod(8, 10) # (0, 8)
divmod(3, 2) # (1, 1)
divmod(2, 2) # (1, 0)
# Sets
a = {1,2,3,4,5}
b = {1,3,5,7}
a.intersection(b) # {1,3,5}
c = a.difference(b)
c # {2, 4}
c.remove(2)
c # {4}
c.pop() # 4
c # set()
# Remove an element from dict and Counter
d = {"a": 2, "b": 1}
del d["a"]
d # {'b': 1}
from collections import Counter
count = Counter("aab")
count # Counter({'a': 2, 'b': 1})
del count["a"]
count # Counter({'b': 1})
# Dict
d = {"a": 2, "b": 1}
d.values() # dict_values([2, 1])
d.keys() # dict_keys(['a', 'b'])
# Dict - setdefault
d = {"foo": 1}
d.setdefault("foo", 2) # 2
d # {'foo': 2}
d.setdefault("bar", 1) # 1
d # {'foo': 1, 'bar': 1}
# d.setdefault("baz", 1) -> is the same as below
if "baz" not in d:
d["baz"]
else:
d["baz"] = 1
# Strings
"a.b+c@x.com".split("@") # ['a.b+c', 'x.com']
"foo+bar+baz".split("+") # ['foo', 'bar', 'baz']
"foo+bar+baz".split("+", 1) # ['foo', 'bar+baz']
"a.b".replace(".", "") # 'ab'
# Timestamps and delta calculation
import time
t1 = time.time()
t1 # 1780560250.7262917
t2 = time.time()
t2 # 1780560253.26109
t2 - t1 # 2.5347983837127686