반응형
Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
05-19 04:57
관리 메뉴

ImJay

[파이썬/Python] 백준 2920번 음계 본문

Solved.ac - Python/CLASS 1+

[파이썬/Python] 백준 2920번 음계

ImJay 2023. 4. 11. 16:34
반응형

[파이썬/Python] 백준 2920번 음계

 

2920번: 음계

다장조는 c d e f g a b C, 총 8개 음으로 이루어져있다. 이 문제에서 8개 음은 다음과 같이 숫자로 바꾸어 표현한다. c는 1로, d는 2로, ..., C를 8로 바꾼다. 1부터 8까지 차례대로 연주한다면 ascending, 8

www.acmicpc.net


문제

다장조는 c d e f g a b C, 총 8개 음으로 이루어져있다. 이 문제에서 8개 음은 다음과 같이 숫자로 바꾸어 표현한다. c는 1로, d는 2로, ..., C를 8로 바꾼다.

1부터 8까지 차례대로 연주한다면 ascending, 8부터 1까지 차례대로 연주한다면 descending, 둘 다 아니라면 mixed 이다.

연주한 순서가 주어졌을 때, 이것이 ascending인지, descending인지, 아니면 mixed인지 판별하는 프로그램을 작성하시오.

 

해설

오름차순일 경우 (list[index] + 1 == list[index+1])

내림차순일 경우 (list[index] - 1 == list[index+1])

둘 다 아닌 경우를 구분하여 출력하면 된다.

코드

import sys

scales = list(map(int, sys.stdin.readline().split()))
check = 0


for i in range(len(scales)-1):
    if scales[i] + 1 == scales[i+1]:
        check = 1
    elif scales[i] - 1 == scales[i+1]:
        check = 2
    else:
        check = 0
        break

if check == 0:
    print('mixed')
elif check == 1:
    print('ascending')
elif check == 2:
    print('descending')

 

풀이

import sys

scales = list(map(int, sys.stdin.readline().split()))
check = 0

1. 음계를 입력 받는다. 오름차순, 내림차순을 구분할 변수도 선언해준다.

 

for i in range(len(scales)-1):
    if scales[i] + 1 == scales[i+1]:
        check = 1
    elif scales[i] - 1 == scales[i+1]:
        check = 2
    else:
        check = 0
        break

2. 오름차순일 경우 (list[index] + 1 == list[index+1]), check = 1

내림차순일 경우 (list[index] - 1 == list[index+1]), check = 2

둘 다 아닌 경우 check = 0

 

if check == 0:
    print('mixed')
elif check == 1:
    print('ascending')
elif check == 2:
    print('descending')

3. check 에 할당된 값에 따라 답을 출력해준다.

 

피드백

order = input().split()
if order == sorted(order):
    print('ascending')
elif order == sorted(order, reverse=True):
    print('descending')
else:
    print('mixed')

sorted 메소드를 생각해냈다면 훨씬 간단하고 쉽게 풀 수 있었다.

오름차순, 내림차순에 특화된 메소드인데 왜 생각 못했을까 아쉽다.

 

참고자료

 

로그인

 

www.acmicpc.net

 

반응형
Comments