和大家分享自己完成的《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核心编程 第二版 答案 非官方

posted on 2011-02-02 01:28  balian  阅读(897)  评论(0编辑  收藏  举报