sfdye / python-for-leetcode

python tricks that will help you with leetcode

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

python-for-leetcode

Python tricks that will help you with leetcode

Tricks

  1. Use Python 3

  2. One-liner Trie

trie = lambda :defaultdict(trie)
trie = trie()

Implement trie prefix tree

  1. Flatten 2D array (matrix)
a = [
  [1,2,3],
  [4,5,6],
  [7,8,9]
]

print(sum(a), [])
  1. 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))))
  1. Tuple unpacking
  1. Boolean as int

  2. map

  3. redeuce

  4. Copy list

a = [1, 2, 3]
b = a[:]
  1. 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)
  1. Swap variables
a, b = b,a
  1. 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

Reference

About

python tricks that will help you with leetcode

License:MIT License