Python

[Python] 예제 : 회문(Palindrom)

SangRok Jung 2022. 8. 29. 21:43
반응형

문제


A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s, return true if it is a palindrome, or false otherwise.

 

 

 

 

출력 예



Example 1:
Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.


Example 2:
Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.


Example 3:
Input: s = " "
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.

 

 

 

 

 

해석


  1. 문자열을 소문자로 변환. -> lower()
  2. 공백 제거. -> replace(" ", "")
  3. 영문자만 추출 -> list(filter(str.isalpha, String)
  4. 리스트를 스트링으로 변환 "".join(list)
  5. 문자열 뒤집기 -> Strig[::-1]

 

s1 = "".join(list(filter(str.isalpha, input("Enter the sentence").lower().replace(" ", ""))))
s2 = s1[::-1]

if s1 == s2 :
    print(" ""%s"" is a palindrome. " % s2)
elif s1 != s2 :
    print(" ""%s"" is not a palindrome. " % s2)

 

반응형

'Python' 카테고리의 다른 글

[python] function  (0) 2022.08.30
[Python] 예제 : 요일 확인 프로그램  (0) 2022.08.30
[Python] 반복문 while  (0) 2022.08.29
[python] 반복문 for  (0) 2022.08.26
[python] 조건문 if  (0) 2022.08.25