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) 이렇게 쓰면 간결하게 범위설정도 되면서 코드도 짧아진다
'프로그래밍 > 알고리즘' 카테고리의 다른 글
브루트포스 알고리즘 (0) | 2023.01.06 |
---|---|
프로그래머스 - 부족한 금액 계산하기 파이썬 (0) | 2023.01.05 |
프로그래머스 - 수박수박수박수박수박수? 파이썬 (0) | 2023.01.02 |
프로그래머스-없는 숫자 더하기 파이썬 (0) | 2022.12.29 |
프로그래머스 - 핸드폰 번호 가리기 파이썬 (0) | 2022.12.28 |
댓글