CODING TEST/Code Tree

[코드트리 조별과제] 4주차 (정렬된 숫자 위치 알아내기 / DateTime to DateTime)

더라 2024. 8. 11. 22:30
728x90

정렬에서 lambda를 사용하는

방법에 연습과

날짜와 시간계산을

시뮬레이션 하지 않고

계산식으로 구하는 연습을

할 수 있던 한 주였다.

 

 

 

 

 

 

 

학습 내용

정렬된 숫자 위치 알아내기

 

[코드트리] 정렬된 숫자 위치 알아내기

 

class Number:
    def __init__(self, num, idx = -1):
        self.num = num
        self.idx = idx

n = int(input())
arr = list(map(int, input().split()))
sequence = [Number(num) for num in arr]

sorted_sequence = sorted(sequence, key = lambda x:x.num)

for i, number in enumerate(sorted_sequence):
    number.idx = i+1

for number in sequence:
    print(number.idx, end =' ')

 

생각한 풀이 방법은 다음과 같다.

 

숫자를 입력 받아 sequence에

객체Number들을 담은 리스트를 만든다.

 

sorted_sequence에

sequence를 오름차순으로 정렬한다.

 

정렬된 상태의 인덱스 값을

Number.idx에 대입한다.

 

sequence에 담긴

Number.idx를 차례대로 출력한다.

 

 

 

 

 

 

728x90

 

 

 


 

DateTime to DateTime

 

[코드트리] DateTime to DateTime

 

풀이1

start_time = 11
d2, h2, m2 = map(int, input().split())

def check_day():
    if start_time<d2:
        return True
    elif start_time==d2 and start_time<h2:
        return True
    elif start_time==d2 and start_time==h2 and start_time<=m2 :
        return True
    else:
        return False

if check_day():
    day = d2 - start_time
    hour = h2 - start_time
    mins = m2 - start_time

    print(day*24*60 + hour*60 + mins)
else:
    print(-1)

 

check_day()

if문을 통해 a일 b시 c분이

11일 11시 11분보다

더 앞서있는지 판별한다.

 

start_time = 11일때

  • start_time < d2
    • 11일 '이후'이기 때문에 연산 o
    • ex) 12일 11시 11분
  • start_time==d2 and start_time<h2
    • 11일 일때, 11시 '이후'이기 때문에 연산 o
    • ex) 11일 12시 11분
  • start_time==d2 and start_time==h2 and start_time<=m2
    • 11일 11시 일때, 11분 '이상'이기 때문에 연산 o
    • ex1) 11일 11시 11분
    • ex2) 11일 11시 20분

d2, h2, m2 에서 각각 start_time을 뺀 값을

day, hour, mins 변수에 담는다.

 

최종적으로 몇분 소요되는지 구한다.

day*24*60 + hour*60 + mins

 

 

 

풀이2

start_time = 11
d2, h2, m2 = map(int, input().split())

mins = (d2 * 24 * 60 + h2 * 60 + m2) - (start_time * 24 * 60 + start_time * 60 + start_time)

if mins < 0:
    print(-1)
else:
    print(mins)

 

풀이2는 풀이1로 문제 해결한 후

해설을 보고 수정한 코드다.

 

풀이1에서 check_day()를 사용해 조건을

설정하는 부분에서 실수가 많았는데,

 

풀이2처럼

mins < 0으로 체크하는 것이

더 좋은 방식인 것 같아 기록한다.

 

입력 받은 시간이

기준시간인 11일 11시 11분 보다 과거면

입력 받은 시간 - 기준 시간의 값이 음수가 된다는 점을

활용하여 해결하는 코드다.

728x90