Skip to content

Commit 197f764

Browse files
author
alisharify
committed
Add Working
1 parent 6f12ed9 commit 197f764

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed

week-7/working/test_working.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import pytest
2+
import working
3+
4+
def test_valid_time():
5+
assert working.convert("9:00 AM to 5:00 PM") == "09:00 to 17:00"
6+
assert working.convert("9:00 AM to 10:00 AM") == "09:00 to 10:00"
7+
8+
def test_value_error():
9+
with pytest.raises(ValueError):
10+
working.convert('09:00 AM to 605:00 PM')
11+
working.convert('05:00 AM 648:00 PM')
12+
13+
with pytest.raises(ValueError):
14+
working.convert(" ")
15+
working.convert(" to ")
16+
working.convert("9:60 AM to 5:80 PM")

week-7/working/working.py

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import re
2+
import sys
3+
4+
5+
def main():
6+
print(convert(input("Hours: ")))
7+
8+
9+
def convert(s):
10+
def is_valid_60_minute(m):
11+
m = int(m)
12+
return True if 59 >= m >= 0 else False
13+
14+
def is_valid_12_hour(h):
15+
h = int(h)
16+
return True if 12 >= h >= 1 else False
17+
18+
def convert_2_24h(flag, h, minute):
19+
if not minute:
20+
minute = 0
21+
hour = int(hour)
22+
23+
if not is_valid_12_hour(hour):
24+
raise ValueError
25+
if not is_valid_60_minute(minute):
26+
raise ValueError
27+
28+
if flag == "am":
29+
if hour == 12:
30+
hour = "00"
31+
else:
32+
hour = str(hour)
33+
new_hour = str(hour)
34+
if flag == "pm":
35+
if hour == 12:
36+
hour = "12"
37+
else:
38+
hour += 12
39+
hour = str(hour)
40+
new_hour = str(hour)
41+
42+
minute = str(minute)
43+
new_hour = hour.zfill(2) # add 0 => 2 =>> 02
44+
new_minute = minute.zfill(2) # add 0
45+
return f"{new_hour}:{new_minute}"
46+
47+
48+
regex = r"^([0-9]{1,2})(\:)?([0-9]{2,2})? (AM|PM)" + " TO " + "([0-9]{1,2})(\:)?([0-9]{1,2})? (AM|PM)$"
49+
result = re.search(regex, s, flags=re.IGNORECASE)
50+
51+
if result:
52+
hour1,colm1,minute1,flag1,hour2,colm2,minute2,flag2 = result.groups()
53+
if not flag1 or not flag2 or not hour1 or not hour2:
54+
raise ValueError
55+
first_time = convert_2_24h(flag1, hour1, minute1)
56+
second_time = convert_2_24h(flag2, hour2, minute2)
57+
return f"{first_time} to {second_time}"
58+
else:
59+
raise ValueError
60+
61+
62+
if __name__ == "__main__":
63+
main()

0 commit comments

Comments
 (0)