class Solution:
def mostVisitedPattern(self, username: List[str], timestamp: List[int], website: List[str]) -> List[str]:
# timestamp 기준으로 정렬
timestamp, username, website = zip(*sorted(zip(timestamp, username, website)))
dic = collections.defaultdict(list)
for i in range(len(username)):
dic[username[i]] += [website[i]]
def findPattern(website, comb):
if comb in self.patterns:
self.count[self.patterns.index(comb)] += 1
elif len(comb) == 3:
self.patterns.append(comb)
self.count.append(1)
return
if len(website) == 0:
return
for i in range(len(website)):
findPattern(website[i+1:], comb + [website[i]])
self.patterns = []
self.count = []
for k, v in dic.items():
findPattern(v, [])
# self.patterns 기준으로 정렬 -> 사전순 작은 값 반환 위해
self.patterns, self.count = zip(*sorted(zip(self.patterns, self.count)))
for i in range(len(self.count)):
if self.count[i] == max(self.count):
return self.patterns[i]
timestamp
기준으로 username
, timestamp
, website
모두 정렬
dic
에 username
과 website
를 mapping
findPattern
함수를 만들어서 각 유저의 website
패턴 조합을 모두 찾기
=> 길이가 3 이 되면 패턴 추가 / 이미 존재하면 패턴 횟수 count + 1
한개 이상의 답이 나올 경우 사전순으로 작은 값을 반환해야하므로
self.patterns
기준으로 self.patterns
, self.count
정렬
self.count
의 max 값과 매칭되는 self.patterns
를 찾아서 return
a, b = zip(*sorted(zip(a, b)))
=>a
를 기준으로a
,b
동시에 정렬
Given an array of strings products and a string searchWord. We want to design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with the searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products.
Return list of lists of the suggested products after each character of searchWord is typed.
class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
products.sort()
newProduct = []
for i in range(len(products)):
if searchWord[0] == products[i][0]:
newProduct.append(products[i])
ans = []
prefix = ""
for i in range(len(searchWord)):
prefix += searchWord[i]
tmp = []
for j in range(len(newProduct)):
if prefix == newProduct[j][:i+1]:
tmp.append(newProduct[j])
if len(tmp) == 3:
break
ans.append(tmp)
return ans
products
정렬 후
searchWord
와 같은 값으로 시작하는 단어들만 newProduct
에 저장
prefix
는 searchWord
의 앞부터 한글자씩 늘려가면서 잡고
newProduct
의 0 ~ i
까지의 값과 같은지 비교
같은 값들은 tmp
에 저장하고 다 찾으면 ans
에 append
찾을 때, 3 개를 모두 찾았으면 break