米哈游笔试题-四则运算

输出连个分数的四则运算,并且将其结果显示正常阅读习惯

"""
 编程题 1 分数的四则运算
"""
def gcd(a, b):
    while (b != 0):
        temp = a % b
        a = b
        b = temp
    return a

def count_result():
    string = input()
    a, o, b = string.split()
    a_fenzi, a_fenmu = [int(t) for t in a.split("/")]
    b_fenzi, b_fenmu = [int(t) for t in b.split("/")]

    if o == "+":
        result_fenzi = a_fenzi * b_fenmu + a_fenmu * b_fenzi
        result_fenmu = a_fenmu * b_fenmu

    if o == "-":
        if a_fenzi == b_fenzi and  b_fenmu == a_fenmu:
            return 0
        result_fenzi = a_fenzi * b_fenmu - a_fenmu * b_fenzi
        result_fenmu = a_fenmu * b_fenmu

    if o == "*":
        result_fenzi = a_fenzi * b_fenzi
        result_fenmu = a_fenmu * b_fenmu

    if o == "/":
        if a_fenzi == b_fenzi and  b_fenmu == a_fenmu:
            return 1
        result_fenzi = a_fenzi * b_fenmu
        result_fenmu = a_fenmu * b_fenzi

    # 分子分母同时除以其最大公约数进行 约分
    max_yueshu = gcd(result_fenzi, result_fenmu)
    result_fenzi = result_fenzi // max_yueshu
    result_fenmu = result_fenmu // max_yueshu

    rstult = str(result_fenzi) + "/" + str(result_fenmu)
    return rstult


if __name__ == "__main__":
    print(count_result())
# 1/8 / 1/8

你可能感兴趣的:(IT笔试题,python,米哈游笔试,四则运算)