Counter로 집합으로 만듦.
from collections import Counter
Counter('hello world')
# Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
def countLetters(word):
counter = {}
for letter in word:
if letter not in counter:
counter[letter] = 0
counter[letter] += 1
return counter
countLetters('hello world'))
# {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
most_common으로 반환
Counter('abracadabra').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]
>>> Counter('abracadabra').most_common(1)
[('a', 5)]
>>> Counter('abracadabra').most_common(2)
[('a', 5), ('b', 2)]
A & B : 교집합
A | B : 합집합
from collections import Counter
def solution(str1, str2):
str1, str2 = FRANCE, french
set1 = Counter([str1[i:i+2].upper() for i in range(0, len(str1)-1) if str1[i:i+2].isalpha()])
set2 = Counter([str2[i:i+2].upper() for i in range(0, len(str2)-1) if str2[i:i+2].isalpha()])
J = lambda A, B: 1 if len(A) == 0 and len(B) == 0 else sum((A & B).values()) / sum((A | B).values())
return int(J(set1, set2) * 65536)
# 16384
lambda : https://www.notion.so/lambda-17c76d7f1f2749a99866cffb59e062dd
(lambda a, b : a + b)(1, 10)
# 11
list(map(lambda x : x + 10, [1, 2]))
# [11, 12]
키로 사용 가능
def solution(numbers):
numbers.sort(key = lambda x : str(x)*3, reverse = True)
return str(int(''.join(list(map(str, numbers)))))
number = [3, 30, 34, 5, 9]
# "9534330"
Counter
가 재밌는 부분은 바로 마치 숫자처럼 산술 연산자를 사용할 수 있다는 것인데요.
예를 들어, 아래와 같이 2개의 카운터 객체가 있을 때,
counter1 = Counter(["A", "A", "B"]) counter2 = Counter(["A", "B", "B"])
이 두 객체를 더할 수도 있고요.
counter1 + counter2
Counter({'A': 3, 'B': 3})
이 두 객체를 뺄 수도 있습니다.