List
- flatten a nested list
https://stackoverflow.com/a/952952/7883783
# to flat the nested list
flat_list = [item for sublist in l for item in sublist]
# shorter, but not efficient, not readable
flat = sum(nums, [])
- creating a dictionary of Lists
from collections import defaultdict
lst = [('Geeks', 1), ('For', 2), ('Geeks', 3)]
orDict = defaultdict(list)
# iterating over list of tuples
for key, val in lst:
orDict[key].append(val)
STRING
- build hash map : character and how often it appears - collections.Counter(s)
from collections import Counter
s = 'abcccc'
count = collections.Counter(s)
print(count)
Counter({'c': 4, 'a': 1, 'b': 1})
#### DICT ####
# delete a key
del a['alice']
# loop key/val
for key, val in a.items():
# loop with val
for val in a.values():
# loop with key (order is random)
for key in a:
# adding dict with checking if the value is in there or not
if count_dic.get(i) is None:
count_dic[i] = 1
else:
count_dic[i] += 1
# or
try:
count_dic[i] += 1
except KeyError:
count_dic[i] = 1
####################
### Linked list ####
####################
# 1. reverse list - iteration
prev = None
while head is not None:
curr_head = head
head = head.next # curr_head refers to the head. the same linked list classes.
curr_head.next = prev
prev = curr_head
return prev
# 2. reverse list - recursive
# https://youtu.be/S92RuTtt9EE
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if (not head) or (not head.next): # base condition - first thing in recursive
return head
p = self.reverseList(head.next)
head.next.next = head
head.next = None
return p
'Software Engineering' 카테고리의 다른 글
리트코드 LeetCode 프리미엄 구독 해지한 이유 (2) | 2023.12.02 |
---|---|
[알고리즘] LCA(Lowest Common Ancestor) 최소공통조상 (0) | 2022.12.02 |
[알고리즘] 이진 검색 binary search (0) | 2022.11.27 |
[알고리즘] 이진검색트리 BST(binary search tree) (0) | 2022.11.25 |
[알고리즘] 이진트리 binary tree DFS, BFS (0) | 2022.11.22 |