반응형
my_str = "abc1Addfggg4556b"
n = 6
답 : ["abc1Ad", "dfggg4", "556b"]
1. range(시작, 끝, 간격) : n개씩 자르기 == 간격이 n인 상황
def solution(my_str, n):
result = []
for i in range(0, len(my_str), n):
if len(my_str[i:i + n]) >= 6:
result.append(my_str[i:i + n])
else:
result.append(my_str[i:len(my_str)])
return result
1-1. slicing의 경우, 범위를 초과해도 에러가 나지 않기 때문에 1번처럼 len()으로 조건을 처리해주지 않아도 되긴 한다.
def solution2(my_str, n):
return [my_str[i:i + n] for i in range(0, len(my_str), n)]
2. while list/string : list/string이 있을 때까지
def solution3(my_str, n):
result = []
while my_str:
if len(my_str) >= n:
result.append(my_str[:n])
my_str = my_str[n:]
else:
result.append(my_str)
my_str = ''
return result
반응형
'프로그래밍 > 알고리즘 & 자료구조' 카테고리의 다른 글
[프로그래머스] 팩토리얼 with 파이썬 (0) | 2023.04.08 |
---|---|
[프로그래머스] 문자열 계산하기 with 파이썬 (0) | 2023.04.07 |
[프로그래머스] 이진수 더하기 with 파이썬 (0) | 2023.04.06 |
[프로그래머스] 컨트롤 제트 with 파이썬 (0) | 2023.04.05 |
[프로그래머스] 7의 개수 with 파이썬 (0) | 2023.04.04 |
댓글