• 《Python核心编程》第二版第97页第五章练习 续四


    和大家分享自己完成的《Python核心编程》答案。
    因为不是来自官方资源,是自己的的练习,可能有误或者并非最好的解决办法。

    5-13.
    转换。写一个函数把小时和分钟所表示的时间转换成为只用分钟表示的时间。
    【答案】
    代码如下:
    def conversion(a, b):
        return a * 60 + b

    time = raw_input('Please input the time in HH:MM format: ... ')
    t = time.split(':')
    print conversion(int(t[0]), int(t[1]))

    5-14.
    银行利息。写一个函数,以定期存款利率为参数,假定该账户每日计算复利,请计算并返回年回报率。
    【答案】
    代码如下:
    dayInterestRate = float(raw_input('Please input the day rate: ... '))
    print (1. + dayInterestRate)**365 - 1

    5-15.
    最大公约数和最小公倍数。请计算两个整型的最大公约数和最小公倍数。
    【背景知识】
    本题答案采用的是更相减损术,又称“等值算法”求两个数的最大公约数,而两个数的最小公倍数是他们的乘积除以最大公约数。
    最小公倍数(Least Common Multiple,缩写LCM)
    最大公约数(Greatest Common Divisor,缩写GCD;或Highest Common Factor,简写为HCF)
    【答案】
    代码如下:
    def GCD(a, b):
        i = 0   
        if (a % 2 == 0) and (b % 2 == 0):
            c = a / 2
            d = b / 2
            i = i + 1
        else:
            c = a
            d = b
        while c != d:
            if c > d: c = c - d
            elif c < d: d = d - c
            else: return c * (2 ** i)
        return c * (2 ** i)

    def LCM(a, b):
        return a * b / GCD(a, b)

    print GCD(4044, 9088)
    print LCM(4044, 9088)

    【参考】求最大公约数的算法
    http://blog.csdn.net/cauwtj/archive/2009/04/02/4043388.aspx
    快速求最小公倍数的四种方法
    http://www.hmtyxx.com/jiaoyu/ShowArticle.asp?ArticleID=1414

    关键词:Pyhon核心编程 第二版 答案 非官方

  • 相关阅读:
    Python封装发送信息到钉钉群
    centos 7.6 安装php70
    小米5s plus刷机
    centos 7 安装webmin
    交易开拓者旗舰版(TB旗舰版)软件升级中如何迁移用户数据
    centos 7.6 修改vim配色方案
    centos 7.0 读写ntfs分区
    centos iptables 数据转发
    centos 7.6 配置VNC
    win下maridb 10.1.8下主从复制配置
  • 原文地址:https://www.cnblogs.com/balian/p/1948815.html
Copyright © 2020-2023  润新知