List of common algorithms in python
def bsearch(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
val = arr[mid]
if val == target:
return mid
elif val > target:
right = mid - 1
else:
left = mid + 1
return -1
import heapq
def heap_min(arr):
heapq.heapify(arr)
return arr[0]
def heap_max(arr):
heaparr = []
for val in arr:
heapq.heappush(heaparr, -1 * val)
return -1 * heaparr[0]
def dfs(root, target):
def search(node):
if not node:
return
if node.val == target:
return node
left = search(node.left)
if left:
return left
right = search(node.right)
if right:
return right
return search(root)
|
defaultdict
|
defaultdict(default_factory=None)
|
|
namedtuple
|
namedtuple('Point', ['x', 'y'])
|
|
deque
|
deque([iterable[, maxlen]])
|
|
append(x)
|
|
|
appendleft(x)
|
|
|
pop()
|
|
|
popleft()
|
|
|
Counter
|
Counter([iterable-or-mapping])
|
|
most_common(n)
|
|
|
subtract([iterable-or-mapping])
|
def bfs(root, target):
queue = [root]
while queue:
node = queue.pop()
if not node:
continue
if node.val == target:
return node
queue.append(node.left)
queue.append(node.right)
return None
|
Slice
|
a[start:stop:step]
|
|
Elements after X
|
a[x:]
|
|
First X elements
|
a[:x]
|
|
Last X elements
|
a[-x]
|
|
Elements from X to Y not inclusive of Y
|
a[x:y]
|
|
Reverse List
|
a[::-1]
|
No comments yet.
Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.