Python/Data Struc & algo

[Python] collections Counter를 이용한 합집합, 교집합, 차집합 구하기

Pydole 2018. 5. 13. 15:25

 

# 합집합

import collections

lst1 = ['a','b','c','a','c','f','g']
tup1 = ('b','d','e','e','f','f','g','h','h')

ct1 = collections.Counter(lst1)
ct2 = collections.Counter(tup1)

print(ct1+ct2)                            # 합집합 요소 갯수 세기
print(list((ct1+ct2).elements()))         # 합집합 리스트
Counter({'f': 3, 'a': 2, 'b': 2, 'c': 2, 'g': 2, 'e': 2, 'h': 2, 'd': 1})
['a', 'a', 'b', 'b', 'c', 'c', 'f', 'f', 'f', 'g', 'g', 'd', 'e', 'e', 'h', 'h']

 

 

# 교집합

import collections

lst1 = ['a','b','c','a','c','f','g']
tup1 = ('b','d','e','e','f','f','g','h','h')

ct1 = collections.Counter(lst1)
ct2 = collections.Counter(tup1)

print(ct1&ct2)                            # 교집합 요소 갯수 세기
print(list((ct1+ct2).elements()))         # 교집합 리스트

Counter({'b': 1, 'f': 1, 'g': 1}) ['b', 'f', 'g']

 

 

# 차집합


import collections

lst1 = ['a','b','c','a','c','f','g']
tup1 = ('b','d','e','e','f','f','g','h','h')

ct1 = collections.Counter(lst1)
ct2 = collections.Counter(tup1)

print(ct1-ct2)                            # 교집합 요소 갯수 세기
print(list((ct1-ct2).elements()))         # 교집합 리스트
Counter({'a': 2, 'c': 2})
['a', 'a', 'c', 'c']

 

 

# 최대값 추출

import collections

lst1 = ['a','b','c','a','c','f','g']
tup1 = ('b','d','e','e','f','f','g','h','h')

ct1 = collections.Counter(lst1)
ct2 = collections.Counter(tup1)

print(ct1|ct2)                            # 유니온. (ct1과 ct2 요소를 비교하여 최대값)
print(list((ct1|ct2).elements()))         # 유니온
Counter({'a': 2, 'c': 2, 'f': 2, 'e': 2, 'h': 2, 'b': 1, 'g': 1, 'd': 1})
['a', 'a', 'b', 'c', 'c', 'f', 'f', 'g', 'd', 'e', 'e', 'h', 'h']