알고리즘에 활용하기 위해 파이썬 string을 비교하는 방법에 대해 알아보자
단순 비교
a = 'a'
b = 'a'
print(a == b) # True
print(id(a) == id(b)) # True
print(a is b)
파이썬에서 string은 불변(immutable) 객체에 해당한다.
불변 객체는 call by value 로 데이터에 접근하기 때문에 값만 같다면 동치가 성립한다.
String의 Character Set 비교
s1="abc def ghi"
s2="def ghi abc"
sorted(list(s1)) == sorted(list(s2)) # True
sorted(list(s1)) # [' ', ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
sorted(list(s2)) # [' ', ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
공백(' '
)을 포함하여 같은 character 집합으로 이루어져있는지 비교한다.
String 내 포함된 단어 비교
s1 = 'abc def ghi'
s2 = 'def ghi abc'
set1 = set(s1.split(' ')) # {'ghi', 'abc', 'def'}
set2 = set(s2.split(' ')) # {'ghi', 'abc', 'def'}
print(set1 == set2) # True
공백을 기준으로 단어를 나눈 후 set 에 저장하여 비교한다.
출처: Stackoverflow
댓글