CS50P week1 problem set

Problem Set 1

官网一共有五题,前面三题较为简单,故不放置代码

Math Interpreter

image-20240203130437549

def main():
    expression = input("Expression: ")
    result = calculate(expression)
    print(result)

def calculate(formula):
    # 注意 split 的用法
    x, y, z = formula.split(" ")
    x = float(x)
    z = float(z)

    if y == "+":
        num = x + z
        return round(num, 1)
    elif y == "-":
        num = x - z
        return round(num, 1)
    elif y == "*":
        num = x * z
        return round(num, 1)
    elif y == "/":
        if z != 0.0:
            num = x / z
            return round(num, 1)
        else:
            return "y can't be zero"
    else:
        return "The expression is not correct"

        
main()



# def calculate(formula):
#     formula = formula.strip()

#     if "+" in formula:
#         num = float(formula[0]) + float(formula[4])
#         return round(num, 1)
#     elif "-" in formula:
#         num = float(formula[0]) - float(formula[4])
#         return round(num, 1)
#     elif "*" in formula:
#         num = float(formula[0]) * float(formula[4])
#         return round(num, 1)
#     elif "/" in formula:
#         if formula[4] != "0":
#             num = float(formula[0]) / float(formula[4])
#             return round(num, 1)
#         else:
#             return "y can't be zero"
#     else:
#         return "The expression is not correct"

Meal Time

image-20240203130515967

image-20240203130526446

def main():
    time_input = input("What time is it? ")
    time_input = convert(time_input)

    if 7.00 <= time_input <= 8.00:
        print("breakfast time")
    elif 12.00 <= time_input <= 13.00:
        print("lunch time")
    elif 18.00 <= time_input <= 19.00:
        print("dinner time")

def convert(time):
    # 12 小时制
    if time.endswith("a.m"):
        time = time.removesuffix("a.m").strip()
        hour, minute = time.split(":")
        hour = float(hour)
        minute = round(float(minute) / 60, 2)
        return hour + minute
    elif time.endswith("p.m"):
        time = time.removesuffix("p.m").strip()
        hour, minute = time.split(":")
        hour = float(hour) + 12.0
        minute = round(float(minute) / 60, 2)
        return hour + minute
    else:
        # 24h 制
        hour, minute = time.split(":")
        hour = float(hour)
        minute = round(float(minute) / 60, 2)
        return hour + minute

# def convert(time):
#     # 24h 制
#     hour, minute = time.split(":")
#     hour = float(hour)
#     minute = round(float(minute) / 60, 2)
#     return hour + minute


if __name__ == "__main__":
    main()
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值