Post

[Algorithm] [PCCP 기출문제] 1번 / 동영상 재생기

[PCCP 기출문제] 1번 / 동영상 재생기

💡 내가 쓴 코드드

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
def solution(video_len, pos, op_start, op_end, commands):
    #분으로 변경
    for s in [video_len, pos, op_start, op_end]:
        s = int(s[:2])*60 + int(s[3:])

    for command in commands:
        #오프닝 사이에 있을 때
        if op_start<=pos<=op_end:
            pos = op_end

        #prev 누를 때
        if command == "prev":
            if pos<10:
                pos = 0
            else:
                pos -= 10

        if command == "next":
            if pos+10>video_len:
                pos = video_len
            else:
                pos += 10

    if pos%60<10:
        return str(pos//60) + ":0" + str(pos%60)
    else:
        return str(pos//60) + ":" + str(pos%60)
  • 실제로 이 코드들 실행하면, TypeError: can only concatenate str (not "int") to str가 발생한다.
  • 이는 처음에 분으로 변경 파트에서 s는 임시값으로 사용되어 실제 변수의 값은 변하지 않기 때문이다.
  • 이는 파이썬에서의 변수 할당 방식for 루프의 동작 원리 때문이다.

💡 실제 값이 변하지 않는 이유

1
2
3
#분으로 변경
    for s in [video_len, pos, op_start, op_end]:
        s = int(s[:2])*60 + int(s[3:])
  • 이 부분에서 s는 임시변수로 for 루프에서만 사용되는 독립적 변수이다.
  • 즉, s는 위 리스트의 값을 복사한 것이며 해당 변수에 직접 접근하지 않은 것이다.
  • 따라서, 아래의 코드로 변경하였다.
1
2
3
4
# 분으로 변경
times = [video_len, pos, op_start, op_end]
times = [int(t[:2]) * 60 + int(t[3:]) for t in times]  # 각 시간을 분으로 변환
video_len, pos, op_start, op_end = times  # 변환된 값을 다시 각 변수에 할당

💡 시:분 으로 바꾸는 포맷 변경

1
2
3
4
if pos%60<10:
    return str(pos//60) + ":0" + str(pos%60)
else:
    return str(pos//60) + ":" + str(pos%60)
  • 이 부분도 실행하면 분만 변경되어 정답이 아니다.
  • 문자열포맷팅 {} 을 사용해 형식을 맞춰주었다.
  • 이때, 02d 를사용해 오른쪽 2자리를 맞췄으며, 부족한 경우 0을 넣도록 했다.

💡 수정된 코드

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
# 분으로 변경
times = [video_len, pos, op_start, op_end]
times = [int(t[:2]) * 60 + int(t[3:]) for t in times]  # 각 시간을 분으로 변환
video_len, pos, op_start, op_end = times  # 변환된 값을 다시 각 변수에 할당

for command in commands:
    # 오프닝 사이에 있을 때
    if op_start<=pos<=op_end:
        pos = op_end

    # prev 누를 때
    if command == "prev":
        if pos<10:
            pos = 0
        else:
            pos -= 10

    if command == "next":
        if pos+10>video_len:
            pos = video_len
        else:
            pos += 10

    if op_start<=pos<=op_end:
        pos = op_end

# 시간을 다시 "MM:SS"    형식으로 변환
minutes = pos // 60
seconds = pos % 60
return f"{minutes:02d}:{seconds:02d}"  # :02d를 사용해 두 자리로 맞춤
This post is licensed under CC BY 4.0 by the author.