[Python] 2 codes, convert working times to 24 hr format. Both works fine when ran manually,...

Discussão em 'Python' iniciado por Stack, Agosto 31, 2025.

  1. Stack

    Stack Membro Participativo

    The automated tester gives a message "correct working.py passes all test_working checks" and on the next line says "expected exit code 0, not 1". Here is the code:

    working.py:

    import re


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


    def convert(s):
    if matches := re.search(r"^(\d{1,2})(?::(\d{1,2}))? (AM|PM) to (\d{1,2})(?::(\d{1,2}))? (AM|PM)$", s):
    from_hr = matches.group(1)
    from_mins = matches.group(2)
    from_mer = matches.group(3)

    to_hr = matches.group(4)
    to_mins = matches.group(5)
    to_mer = matches.group(6)

    final = f"{to_global(from_hr, from_mer, from_mins)} to {to_global(to_hr, to_mer, to_mins)}"

    return final
    else:
    raise ValueError


    def to_global(hr, mer, mins):
    if mins is None:
    mins = "00"
    if int(hr) < 1 or int(hr) > 12 or int(mins) < 0 or int(mins) >= 60:
    raise ValueError

    if mer == "AM":
    if hr == "12":
    return f"00:{int(mins):02}"
    else:
    return f"{int(hr):02}:{int(mins):02}"
    else:
    if hr == "12":
    return f"12:{int(mins):02}"
    else:
    return f"{int(hr)+12:02}:{int(mins):02}"


    if __name__ == "__main__":
    main()


    test_working.py:

    from working import convert

    import pytest

    def test_convert_without_min():
    assert convert("9 AM to 5 PM") == "09:00 to 17:00"
    assert convert("12 PM to 1 AM") == "12:00 to 01:00"
    assert convert("12 PM to 12 AM") == "12:00 to 00:00"

    def test_convert_with_min():
    assert convert("9:00 AM to 5:00 PM") == "09:00 to 17:00"
    assert convert("09:00 AM to 05:00 PM") == "09:00 to 17:00"
    assert convert("12:00 PM to 1:56 AM") == "12:00 to 01:56"
    assert convert("12:12 PM to 12:00 AM") == "12:12 to 00:00"

    def test_convert_invalid_time():
    with pytest.raises(ValueError):
    convert("9:60 AM to 5:60 PM")
    with pytest.raises(ValueError):
    convert("09:-1 AM to 05:80 PM")
    with pytest.raises(ValueError):
    convert("13:00 AM to 34:70 PM")

    def test_convert_re_error():
    with pytest.raises(ValueError):
    convert("9 AM - 10 AM")
    with pytest.raises(ValueError):
    convert("9 to 5")
    with pytest.raises(ValueError):
    convert("9:00 AM - 5:00 PM")

    Continue reading...

Compartilhe esta Página