Skip to content

Instantly share code, notes, and snippets.

@wmhtet
Created June 23, 2020 06:25
Show Gist options
  • Save wmhtet/8a8a35d4ebf8a8ea891650f744a68031 to your computer and use it in GitHub Desktop.
Save wmhtet/8a8a35d4ebf8a8ea891650f744a68031 to your computer and use it in GitHub Desktop.
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def __repr__(self):
return "TreeNode({},{}, {})".format(self.val, self.left, self.right)
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Node:
def __init__(self, val, neighbors):
self.val = val
self.neighbors = neighbors
def __repr__(self):
return "Node({},{})".format(self.val, self.neighbors)
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.ls = []
self.dic = dict()
def get(self, key: int) -> int:
if key in self.dic:
if self.ls and self.ls[0] == key:
self.ls.pop(0)
self.ls.append(key)
return dic[key]
return -1
def put(self, key: int, value: int) -> None:
while len(self.dic) >= self.capacity and len(self.ls) >= self.capacity:
temp = self.ls.pop(0)
if temp in self.dic:
del self.dic[temp]
self.dic[key] = value
def print_l(*lls):
result = [list() for _ in range(len(lls[0]))]
for ls in lls:
for i, l in enumerate(ls):
if result[i]:
result[i] += "|"
result[i] += l
print("----")
for r in result:
print(r)
print("----")
def print_tree(root: TreeNode):
ls = []
from collections import deque
q = deque()
q.append(root)
dic = {}
large = 4
while q:
level = []
for _ in range(len(q)):
node = q.popleft()
if not node:
level.append(None)
continue
level.append(node.val)
large = max(large, node.val // 10)
dic.setdefault(node.val, [])
dic[node.val].append(node.left)
dic[node.val].append(node.right)
q.append(node.left)
q.append(node.right)
ls.append(level)
*ls, t = ls
fmt = "{:^" + str(large) + "}"
space = " " * large
mid = 2 ** (len(ls) - 2)
if mid < 1:
mid = 1
# print('s:---------')
for level in ls:
print(space * mid, end="")
send = space * mid
if mid == 0:
send = " "
mid = mid // 2
# print(send)
for item in level:
if not item:
item = "None"
print(fmt.format(item), end=send)
print()
print('t:---------\n')
def get_tree_node_levelorder(levelorder):
if not levelorder: return None
from collections import deque
root = TreeNode(levelorder[0])
q = deque()
q.append(root)
count = 0
cl = len(levelorder)
while q:
for _ in range(len(q)):
if count + 1 >= len(levelorder):
q.clear()
break
r = q.popleft()
if levelorder[count + 1] is not None:
r.left = TreeNode(levelorder[count + 1])
q.append(r.left)
if count + 2 < cl and levelorder[count + 2] is not None:
r.right = TreeNode(levelorder[count + 2])
q.append(r.right)
count += 2
return root
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment