본문 바로가기
프로그래밍/알고리즘

프로그래머스 - 문자열 다루기 기본 파이썬

by monicada 2023. 1. 4.
728x90

문제

 

처음 풀이(틀림)

def solution(s):
    if (len(s) == 4 or 6) and s.isdigit():
        return True
    else:
        return False

틀린 이유는 len(s)==4까지는 문자열의 길이가 4인지 판별하지만, 'or 6'부분은 무조건 True가 나오기 때문에 틀린다 

 

성공한 풀이

def solution(s):
    if (len(s) == 4 or len(s) == 6) and s.isdigit():
        return True
    else:
        return False

두 번째 줄처럼 len(s) == 4 or len(s) == 6이라고 따로 명시를 해주어야 문자열 길이의 비교가 된다 

 

다른 간결한 풀이 

#1
def solution(s):
    return s.isdigit() and len(s) in (4,6)

#2
solution = lambda s: s.isdigit() and len(s) in (4,6)

#3
solution = lambda s: True if len(s) in (4,6) and s.isdigit() else False

len(s) in (4,6) 이렇게 쓰면 간결하게 범위설정도 되면서 코드도 짧아진다 

댓글