我正在开发一个需要两个输入的程序。第一个是时间(24小时制),如12:30或14:00,第二个输入是经过的时间(以分钟为单位),如30或90(因此显示1:00或15:30)
我的主要问题是我有很多if / else语句,而且我认为我可能效率很低。我希望有人可以帮我弄清楚我需要考虑的所有特殊情况。如果您给出不会使小时更改两次的数字,该程序目前有效。我真的可以使用一些帮助来提高效率。我在代码中尽可能地评论,以帮助您理解我对每行代码的意图。
代码:
# Taking User Input
startTime = input()
duration = int(input())
# Splitting up the hour and minutes by the colon
rawTime = startTime.split(':')
# Assigning the hour and the minute variables
hourHand = int(rawTime[0])
minuteHand = int(rawTime[1])
# Giving the remainder when you add the minutes and the duration (so
# if it goes over 60 you know by how much)
newMinuteHand = (minuteHand+duration)%60
# Checking to see if newMinuteHand is greater than 0, meaning it goes
# into the next hour.
# Also checking to make sure the hour is not 23:00 or close to
# midnight because that carries over
# to 0:00
if newMinuteHand >= 0 and hourHand != 23:
newHourHand = hourHand + 1
# A couple statements needed here to correctly format the minute
# side.
if newMinuteHand >= 10:
newTime = str(newHourHand) + ':' + str(newMinuteHand)
print(newTime)
else:
newTime = str(newHourHand) + ':0' + str(newMinuteHand)
print(newTime)
# Checking for the case that the hour is 23:00
elif newMinuteHand >= 0 and hourHand == 23:
newHourHand = 0
if newMinuteHand >= 10:
newTime = str(newHourHand) + '0:' + str(newMinuteHand)
print(newTime)
else:
newTime = str(newHourHand) + '0:0' + str(newMinuteHand)
print(newTime)
答案 0 :(得分:1)
你应该可以这样:
hourHand = 23
minuteHand = 00
duration = 61
total_minutes = minuteHand + duration
additional_hours = int(total_minutes / 60)
final_minutes = total_minutes % 60
final_hours = (hourHand + additional_hours) % 24
final_time = "{0}:{1}".format(final_hours,str(final_minutes).rjust(2,"0"))
print(final_time)
但是你还没有明确指出你的输入和输出足以让我知道。
在分钟上使用rjust(2,“0”)可以防止你使用if blah<的if语句10或者你在做什么。
其他一切都应该由除法和模数运算符来处理。