New course! Every coder should learn Generative AI!
Try a free lesson+ 3
This is my solution to the "Military Time" Sololearn code coach! I have a question, though...
So yeah, the code you can see is my solution to the problem. I still feel like it's a bit messy solution... Do you have any idea of how I could have made it easier to read and maybe even in a faster way? CODE > https://code.sololearn.com/c6VYghClG8HS/#py
5 Answers
+ 1
Your solution is not entirely correct. Perhaps that is the reason why the solution you found seems weird to you. But, in fact, it handles the special cases that you don't. For example 12:33 AM ought to translate to 00:33.
What you could think of in situations that require you to verify a certain string format and splitting it into components is: regular expressions. To make things more readable, I'd advise to use variable names that say what they stand for, for example a boolean var named "is_am" or "is_morning_time". If you later write "if (is_am): ..." you know exactly what the if statement expresses.
+ 1
Actually, I found this weird solution on the internet... Still, what are your ideas?
a=input()
b=a.replace("AM","").replace ("PM","")
ans=""
if a[-2:]=="AM":
if b[1]==":":
print("0"+b[0:])
elif b[:2] == "12":
print("00" + b[2:])
else:
print(b[0:])
else:
if b[1]==":":
ans=str(int(b[0])+12)+b[1:]
elif b[2]==":" and b[0:2]!="12":
ans=str(int(b[0:2])+12)+b[2:]
else:
ans= b
print(ans)
+ 1
Ani Jona 🕊 Thank you so much for your feedback!
I modified the code, could you please tell me if it's correct now?
+ 1
If you are searching for a less messy solution for similar problems like these, where time or date calculations are being done. you could use the necessary libraries for it and you could save yourself some time. Here my solution: https://code.sololearn.com/cpX0tO6fFHsr/?ref=app
+ 1
Still not quite. Now you have removed the case of single digit hours in the morning. E.g. 9:00 has to turn into 09:00.