Issue
I know there are lot of answers available on the S/O web, but i am experiencing an unusual error in the HackerRank python 3 shell with the below code which works fine in Jupyter notebook.
time1=input()
l=time1.split(':')
if 'PM' in l[2]:
l[0]=int(l[0])+12
l[2]=l[2].rstrip('PM')
elif 'AM' in l[2]:
l[2]=l[2].rstrip('AM')
if l[0]=='12':
l[0]="0"
time2=''
for i in range(2):
time2+=str(l[i])+':'
time2+=l[2]
print(time2)
This is the challenge:
Given a time in 12-hour AM/PM format, convert it to military (24-hour) time.
Note:
- 12:00:00AM on a 12-hour clock is 00:00:00 on a 24-hour clock.
- 12:00:00PM on a 12-hour clock is 12:00:00 on a 24-hour clock.
Example
s = '12:01:00PM'
Return '12:01:00'.
s = '12:01:00AM'
Return '00:01:00'.
Function Description
Complete the
timeConversion
function in the editor below. It should return a new string representing the input time in 24 hour format.
timeConversion
has the following parameter(s):
- string s: a time in 12 hour format
Returns
- string: the time in 12 hour format
Input Format
A single string s that represents a time in 12-hour clock format (i.e.: hh:mm:ssAM or hh:mm:ssPM).
Constraints
- All input times are valid
Sample Input 0
07:05:45PM
Sample Output 0
19:05:45
I did try to run the same cases which gave errors on the H/R but worked alright on the J/P notebook.
P.S. I know this might be a super basic question I've come up with but please pardon me, I am still a newbie :)
Solution
There seem to be two issues:
- When the input has 12:00:00PM, your code returns an invalid result (24:00:00). It should in that case leave the 12 untouched.
- When the input has 12:00:00AM, your code returns the hour with only 1 digit, while 2 are required.
So change this:
l[0] = int(l[0]) + 12
to:
if l[0] != "12":
l[0] = int(l[0]) + 12
And change this:
l[0] = "0"
to:
l[0] = "00"
With that it will work. Note that you are asked to write the body of the timeConversion
function, so you should not have a hardcoded time1=
in your code.
The final code could be like this:
def timeConversion(time1):
h = time1[0:2]
if time1[-2:] == "PM'":
if h != "12":
h = str(int(h) + 12)
elif h == '12':
h = "00"
return h + time1[2:-2]
Answered By - trincot
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.