Python tricks that will help you with leetcode
-
Use Python 3
-
One-liner Trie
trie = lambda :defaultdict(trie)
trie = trie()
- Flatten 2D array (matrix)
a = [
[1,2,3],
[4,5,6],
[7,8,9]
]
print(sum(a), [])
- Reverse a list or string
str = "abcde"
print(str[::-1])
a = [1, 2, 3, 4, 5]
print(a[::-1])
5: Array index trick (e.g. Palindrome checking)
# Before
str = "abcba"
n = len(str)
print(all(str[i] == str[n-i-1] for i in range(n)))
# After
str = "abcba"
print(all(str[i] == str[~i] for i in range(len(str))))
- Tuple unpacking
-
Boolean as int
-
map
-
redeuce
-
Copy list
a = [1, 2, 3]
b = a[:]
- Dictionary defualt value
# Before
d = {} # dictionary of list
if k in d:
d[k].append(v)
else:
d[k] = [v]
# After
# 1. setdefault method on dict
d = {} # dictionary of list
d.setdefault(k, []).append(v)
# 2. collections.defaultdict
d = collections.defaultdict(list)
d[k].append(v)
- Swap variables
a, b = b,a
- Chained boolean comparisons
if 1 < 2 < 3:
if 'a' < 'c' > 'b':
if 1 == True != False:
Todo:
- zip
- float("inf")
- itertools.zip_longest
- collections.Counter
- heapq
- list as queue
- collections.deque as stack
- string.split
- itertools.chain
- yield in recursion
- sort vs sorted
- sort tuple, sort by key
- range vs xrange
- string.join
- bisect
- list initialzation (using asterisk and anti-pattern)
- enumerate
- Fix markdown syntax
- Add example problems to each trick
- https://github.com/brennerm/PyTricks
- Leetcode problem discussions (especially comments from Stefan Pochmann)