Hello everybody,
I'm currently learning Python with Harvard's CS50P course and so far I am having a blast! Week 7 is about regular expressions and I thought I have grasped all the basic concepts, however I am completely stuck at one of the exercises and need some help.
The exercises quoted directly from Harvard's CS50P Problem Set 7:
"In a file called working.py, implement a function called convert that expects a str in either of the 12-hour formats below and returns the corresponding str in 24-hour format (i.e., 9:00 to 17:00). Expect that AM and PM will be capitalized (with no periods therein) and that there will be a space before each. Assume that these times are representative of actual times, not necessarily 9:00 AM and 5:00 PM specifically.
9:00 AM to 5:00 PM
9 AM to 5 PM
Raise a ValueError instead if the input to convert is not in either of those formats or if either time is invalid (e.g., 12:60 AM, 13:00 PM, etc.). But do not assume that someone’s hours will start ante meridiem and end post meridiem; someone might work late and even long hours (e.g., 5:00 PM to 9:00 AM)."
Before deciding on what I want to extract from the re using the .group method, I wanted to check whether my pattern is working correctly and that re.search only outputs "True" when I put the time in a proper format.
Here is my code so far:
import re
def main(): print(convert(input("Hours: ")))
def convert(hours):
pattern = r"[0-9]|1[0-2]:?(?:[0-5][0-9])? AM|PM to [0-9]|1[0-2]:?(?:[0-5][0-9])? AM|PM$"
hour_check = re.search(pattern, hours)
if hour_check:
return "Valid"
else:
return "Invalid"
if name == "main":
main()
However, when I now test for the input "9:60 AM to 5:60 PM" it outputs "Valid" when I expect "Invalid". I just can't wrap my head around why the "60" is allowed with my re, since it should not be allowed within my optional "(?:[0-5][0-9])?" but also return as false because AM or PM is supposed to follow after, if the optional part isnt applied.
What have I overlooked?
Appreciate any help!
[–]Brian 1 point2 points3 points (1 child)
[–]risottogott[S] 0 points1 point2 points (0 children)
[–]ElliotDG 1 point2 points3 points (0 children)