
from collections import defaultdict
def count_letters(word):
counter = defaultdict(int)
for letter in word:
counter[letter] += 1
return counter
from collections import defaultdict
def count_letters(word):
counter = defaultdict(lambda:0)
for letter in word:
counter[letter] += 1
return counter
from collections import defaultdict
def group_words(words):
grouper = defaultdict(list)
for word in words:
length = len(word)
grouper[length].append(word)
return grouper
Q : 만일 중복되지 않은 단어만 필요
from collections import defaultdict
def group_words(words):
grouper = defaultdict(set)
for word in words:
length = len(word)
grouper[length].add(word)
return grouper
참고한 블로그

Input: equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]]
Output: [6.00000,0.50000,-1.00000,1.00000,-1.00000]
Explanation:
Given: a / b = 2.0, b / c = 3.0
queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ?
return: [6.0, 0.5, -1.0, 1.0, -1.0 ]
note: x is undefined => -1.0
class Solution(object):
def calcEquation(self, equations, values, queries):
G = collections.defaultdict(dict)
for (x,y) ,v in zip(equations, values):
G[x][y] = v
G[y][x] = 1/v
def bfs(src, dst):
# 출발점이나 목적지가 그래프에 없는 경우
if src not in G or dst not in G:
return -1.0
# 큐 초기화: (현재 노드, 현재까지의 계산된 값)
queue = collections.deque([(src, 1.0)])
visited = set() # 방문한 노드를 추적하기 위한 집합
while queue:
current_node, current_value = queue.popleft()
# 목적지에 도달한 경우
if current_node == dst:
return current_value
visited.add(current_node)
# 현재 노드와 연결된 모든 이웃을 확인
for neighbor, weight in G[current_node].items():
if neighbor not in visited:
queue.append((neighbor, current_value * weight))
# 경로를 찾지 못한 경우
return -1.0
return [bfs(s, d) for s, d in queries]