I am attempting to finish the problem set. I have posted the code, and the testing code I've written. The check50 passes my main program, but fails the testing code, I have posted the check50 result below as well. Kindly guide me on what could be the error.

Main code - working.py

import re, sys

def main():
    print(convert(input("Hours: ")))

# Check if the string provided is in recognized format
def s_is_valid_format(s):
    if (matches := re.search(r'^(1?[1-9](:[0-5][0-9])? [AP]M to 1?[1-9](:[0-5][0-9])? [AP]M)$', s)) == None:
        return True
    return False

# Return only the relevant time
def return_time(s):
    return re.search(r'^(1?[1-9]):?([0-5][0-9])? ([AP]M) to (1?[1-9]):?([0-5][0-9])? ([AP]M)$', s).groups()

# Check if the time values are valid
def check_valid_time(time):
    if int(time[0]) < 1 or int(time[0]) > 12:
        raise ValueError
    if int(time[3]) < 1 or int(time[3]) > 12:
        raise ValueError

def convert_hour(hour, meridian):
    if meridian == 'AM':
        if int(hour) == 12:
            return '0'.rjust(2, '0')
        return hour.rjust(2, '0')
    elif meridian == 'PM':
        if int(hour) == 12:
            return '12'
        return str(int(hour) + 12).rjust(2, '0')

def convert(s):
    # Check if the s is of valid format
    if s_is_valid_format(s):
        raise ValueError("Invalid format")

    time = return_time(s)

    # Get the format type, whether long fmt/short fmt

    # Convert the time
    if None in time:
        return f'{convert_hour(time[0], time[2])}:00 to {convert_hour(time[3], time[5])}:00'
        return f'{convert_hour(time[0], time[2])}:{time[1]} to {convert_hour(time[3], time[5])}:{time[4]}'

if __name__ == '__main__':

test code - test_working.py

from working import convert
import pytest

def test_format():
    with pytest.raises(ValueError):
        convert('9 AM - 5 PM')

def test_format_2():
    with pytest.raises(ValueError):
        convert('09:00 AM - 17:00 PM')

def test_time():
    with pytest.raises(ValueError):
        convert('13 AM to 9 PM')
    with pytest.raises(ValueError):
        convert('5 AM to 0 PM')
    with pytest.raises(ValueError):
        convert('5:60 AM to 11:30 PM')
    with pytest.raises(ValueError):
        convert('5:30 AM to 11:90 PM')

def test_return_value():
    assert convert('5 AM to 9 PM') == '05:00 to 21:00'
    assert convert('5:30 AM to 9:30 PM') == '05:30 to 21:30'

def test_return_value2():
    assert convert('5 AM to 9 PM') != '5:0 to 21:00'
    assert convert('5:30 AM to 9:30 PM') != '5 to 9'

def main():

if __name__ == '__main__':

check50 result

check50 test result

1 Answer 1


The input specification requires space between the hh:mm and AM/PM. For example '5 AM to 9 PM' is OK, but '5AM to 9PM' is an invalid input. You are missing a test for this invalid time format.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .