enumerate: index와 index의 값을 함께 반환

백아름·2023년 10월 1일
0

python

목록 보기
26/28
def solution(code):
    mode = 0  # 초기 mode는 0
    ret = ""  # 반환할 문자열 초기화

    for idx, char in enumerate(code):
        if char == "1":  # mode 변경
            mode = 1 - mode
        else:
            # mode가 0이고 idx가 짝수일 때
            if mode == 0 and idx % 2 == 0:
                ret += char
            # mode가 1이고 idx가 홀수일 때
            elif mode == 1 and idx % 2 == 1:
                ret += char

    # ret가 빈 문자열일 경우 "EMPTY" 반환
    if not ret:
        return "EMPTY"
    return ret

# 테스트
print(solution("010101"))  # 예상 출력: "01"
print(solution("0000"))    # 예상 출력: "00"
print(solution("1111"))    # 예상 출력: "EMPTY"

profile
곧 훌륭해질 거에요!

0개의 댓글