[Python] Working on simplifying my project work for easier testing for cs50. I feel like I'm...

Discussão em 'Python' iniciado por Stack, Setembro 26, 2024.

  1. Stack

    Stack Membro Participativo

    In problem set 5 of CS50 ReFueling I am being asked to write a program that has two functions. One that converts a string from "x/y" format into an integer, and another that takes the integer and outputs is as either full empty or the int formatted with a percentage at the end. I think my solution is workable but hard to read am looking for help on how to simplify my program while still being able to thoroughly test it.

    My solution

    def main():
    while True:
    fraction = input("Fraction: ")
    percentage = convert(fraction)
    if isinstance(percentage, float) == True:
    print(gauge(percentage))

    def convert(fraction):
    if isinstance(fraction, int):
    raise ValueError
    fraction = fraction.split("/")
    if fraction[1] == "0":
    raise ZeroDivisionError
    x = int(fraction[0])
    y = int(fraction[1])
    if not isinstance(x, int) or not isinstance(y, int):
    raise ValueError
    frac_value = int(x) / int(y)
    percentage = frac_value * 100
    if percentage > 100:
    raise ValueError
    else:
    return percentage


    def gauge(percentage):
    if percentage <= 1:
    return "E"
    elif percentage >= 99:
    return "F"
    else:
    return f"{round(percentage)}%"


    if __name__ == "__main__":
    main()



    And these are my current tests

    import pytest
    from fuel import convert, gauge

    def test_convert_returns_int():
    assert convert("1/2") == 50

    def test_convert_valueerror():
    with pytest.raises(ValueError):
    convert(2)

    def test_convert_zde():
    with pytest.raises(ZeroDivisionError):
    convert("1/0")

    def test_gauge_returns_E():
    assert gauge(1) == "E"

    def test_gauge_returns_F():
    assert gauge(99) == "F"

    def test_gauge_returns_str_w_percentage():
    assert gauge(30) == "30%"

    Continue reading...

Compartilhe esta Página