문제
https://www.acmicpc.net/problem/13223
13223번: 소금 폭탄
첫째 줄에는 현재 시각이 hh:mm:ss로 주어진다. 시간의 경우 0≤h≤23 이며, 분과 초는 각각 0≤m≤59, 0≤s≤59 이다. 두 번째 줄에는 소금 투하의 시간이 hh:mm:ss로 주어진다.
www.acmicpc.net
정말 부끄러운 코드지만 성장을 위해서 올려본다.
hourlist=list(map(int,input().split(':')))
saltthrowhour=list(map(int,input().split(':')))
outputlist=[0,0,0]
def subtracttime(listnumber):
maxtime=60
if listnumber==0:
maxtime=24
if (saltthrowhour[listnumber]-hourlist[listnumber])<0:
outputlist[listnumber]=(maxtime+saltthrowhour[listnumber]-hourlist[listnumber])
saltthrowhour[listnumber-1]-=1
elif (saltthrowhour[listnumber]-hourlist[listnumber])==0:
outputlist[listnumber]=0
else:
outputlist[listnumber]=(saltthrowhour[listnumber]-hourlist[listnumber])
if listnumber!=2 and (saltthrowhour[listnumber+1]-hourlist[listnumber+1]<0):
if listnumber==1 and outputlist[listnumber-1]<=0:
outputlist[listnumber-1]=maxtime-1
subtracttime(2)
subtracttime(1)
subtracttime(0)
if outputlist[0]==0 and outputlist[1]==0 and outputlist[2]==0:
outputlist[0]=24
outputlist[1]=0
outputlist[2]=0
output=list(map(str,outputlist))
for a in range(3):
output[a]=output[a].zfill(2)
print(output[0]+':'+output[1]+':'+output[2])
그래도 그나마 코드 줄 수를 줄이겠다고 함수를 사용했는데 너무 중구난방해졌다.
00:00:00분이 24:00:00으로 표현되야하는 조건을 보지 못해 틀렸습니다를 몇번을 했다. 앞으로는 조건을 잘 보고 문제를 풀도록 하자 (if문으로 00:00:00분을 24:00:00으로 표현시킨 것도 부끄럽다..)
now = list(map(int, input().split(':'))) # 현재 시간
salt= list(map(int, input().split(':'))) # 소금 투하 시간
# 현재 시간과 소금 투하 시간 초로 환산
now_time = now[0] * 3600 + now[1] * 60 + now[2]
salt_time = salt[0] * 3600 + salt[1] * 60 + salt[2]
if now_time >= salt_time : # 조건에 해당하면
salt_time += 24 * 3600 # 24시간의 초를 더함
result = salt_time - now_time # 경과 시간
hh = str(result // 3600).zfill(2)
mm = str((result % 3600) // 60).zfill(2)
ss = str(result % 60).zfill(2)
print('{}:{}:{}'.format(hh, mm, ss))
다른 사람의 코드다. 나처럼 시간을 시,분,초로 나눠서 한 것이 아닌 시,분을 모두 초로 만들어서 계산했다. 깔끔한 계산인 것 같다.
이 문제를 풀며 zfill()이라는 함수를 사용했는데 zfill()이라는 함수는 문자열 앞을 0으로 채우는 함수로 숫자 형태의 값에서 호출하게 되면 에러가 발생한다. 코딩 문제 풀 때 유용하게 사용할 것 같다.
zfill() 함수를 호출할 때는 인수를 설정하게 되는데 설정한 인수는 자리수를 의미한다.
지정한 자리수보다 대상 문자열 길이가 긴 경우에는 아무런 변화가 일어나지 않는다.
문자열 앞에 +나 -가 기호가 있는 경우에는 +,-를 앞에 넣고 0을 채워주며 +,- 기호도 자리수에 포함되어 계산한다.
str='-123'
ex) print(str.zfill(8))
=>-0000123
문자열 안에 숫자가 아닌 문자를 대입해도 0을 채워준다.
'알고리즘 공부' 카테고리의 다른 글
백준 1110번 (0) | 2022.11.29 |
---|---|
백준 4344번, range(int(input())) list()[1:] (0) | 2022.11.28 |
백준 10951번, try except (0) | 2022.11.27 |
백준 11720번, strip()과 list의 for문을 이용한 사용 (0) | 2022.11.25 |
백준 10992번 (0) | 2022.11.17 |
댓글