[python] palindrome 판별과 N-gram 만들기

palindrome 판별하기

# palindrome은 순서를 거꾸로 읽어도 제대로 읽은 것과 같은 단어나 문장을 말한다.
# 예를 들어, level, sos같은 것들이 회문이다.
word = input()

# i번째 문자와 뒤에서 i번째 문자가 모두 같다면 palindrome이다.
is_palindrome = True
for i in range(len(word) // 2):
    if word[i] != word[-1 - i]:
        is_palindrome = False
        break

print('By loop:', is_palindrome)

# 시퀀스 객체의 슬라이스를 활용해서 더 쉽게 palindrome을 판별할 수 있다.
print('By slicing:', word == word[::-1])

# 반복 가능한 객체의 요소 순서를 반대로 뒤집는 reversed를 사용해도 된다.
print('By reversing:', list(word) == list(reversed(word)))

# 문자열의 join 메소드를 이용해서 판별할 수도 있다.
print('By join:', word == ''.join(reversed(word)))

N-gram 만들기

# N-gram은 문자열에서 N개의 연속된 요소를 추출하는 방법이다.
text = 'python'

# 2-gram이라면 문자열 끝까지 한글자씩 이동하면서 2글자를 추출한다.
for i in range(len(text) - 1):
    print(text[i], text[i + 1], sep='')  # py yt th ho on

# 단어 단위로 N-gram을 만들 수도 있다.
text = 'this is python'
words = text.split()
for i in range(len(words) - 1):
    print(words[i], words[i + 1])  # this is    is python

# zip 함수로 2-gram을 만들 수도 있다.
text = 'python'
two_gram = zip(text, text[1:])  # 'python' 과 'ython' 의 각 요소를 묶어서 튜플로 만든다.
for i in two_gram:
    print(i[0], i[1], sep='')

# zip 함수를 이용해 단어 단위 2-gram 만들기
text = 'this is python'
words = text.split()
for i in range(len(words) - 1):
    print(words[i], words[i + 1])

# zip과 리스트 표현식으로 N-gram을 만들기
text = 'hello'
tmp = [text[i:] for i in range(3)]  # ['hello', 'ello', 'llo']
# zip에는 반복 가능한 객체 여러 개를 콤마로 구분해서 넣어줘야 하는데, tmp는 요소가 3개 들어있는 리스트 1개이기 때문에
# 리스트 앞에 * 을 붙여서 리스트 언패킹을 해줘야한다.
three_gram = zip(*tmp)
for i in three_gram:
    print(i[0], i[1], i[2], sep='')

Updated:

Leave a comment