본문 바로가기

컴퓨터/파이썬 알고리즘 인터뷰

5. Palindrome

import collections

def isPalindrome(s: str) -> bool:
    # 자료형 데크로 선언
    strs: Deque = collections.deque()
    for char in s:
        if char.isalnum():
            strs.append(char.lower())

    # 팰린드롬 여부 판별
    while len(strs) > 1:
        if strs.popleft() != strs.pop():
            return False
    
    return True

string = 'abcba'
ans = isPalindrome(string)
print(ans)
>>> True

https://docs.python.org/3/library/typing.html#typing.TypeVar

 

typing — Support for type hints — Python 3.8.5 documentation

typing — Support for type hints Source code: Lib/typing.py Note The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc. This module provides runtime supp

docs.python.org

3행에서

def isPalindrome(s: str) -> bool:

s: str과 -> bool은 일종의 type hint로 다음과 같은 뜻을 가지고 있다.

s: str은 argument로 문자열을 받는다고 설명해주고 있고,

->bool은 return 할 때 bool 형을 반환한다고 명시하는 역할을 한다. 

 

마찬가지로 5행에서,

strs: Deque = collections.deque()

strs: Deque는 strs이라는 argument가 Deque형으로 선언된다는 것을 명시해주고 있음을 알려준다.

 

그래서 이러한 type hint는 없어도 잘만 동작한다.

 


.https://docs.python.org/3/library/stdtypes.html?highlight=isalnum#bytearray.isalnum

 

Built-in Types — Python 3.8.5 documentation

The following sections describe the standard types that are built into the interpreter. The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions. Some collection classes are mutable. The methods that add, subtract,

docs.python.org

 

if char.isalnum():

isalnum()은 파이썬의 내장함수 중 하나로, 영문자, 숫자 여부를 판별하는 함수로, 이를 이용해 해당하는 문자만 추가할 수 있다. 만약 숫자, 소문자, 대문자가 들어갔다면 True, 공백 등의 이외의 문자가 들어갔다면 False를 반환한다.

 

'Return True if all bytes in the sequence are alphabetical ASCII characters or ASCII decimal digits and the sequence is not empty, False otherwise'

'컴퓨터 > 파이썬 알고리즘 인터뷰' 카테고리의 다른 글

7. 최댓값과 최솟값  (0) 2020.08.27
6. 문자열 슬라이싱  (0) 2020.08.25
4. defaultdict 객체  (0) 2020.08.25
3. is와 ==  (0) 2020.08.24
2. pass  (0) 2020.08.24