《Python核心编程》第二版第308页第十一章练习 续四 -Python核心编程答案-自己做的-

时间:2023-02-13 16:09:46

本博客列出的答案不是来自官方资源,是我自己做的练习,如果有疑问或者错误,欢迎讨论。

11-16.
更新easyMath.py。这个脚本,如例子11.1描绘的那样,以入门程序来帮助年轻人强化他们的数学技能。通过加入乘法作为可支持的操作来更进一步提升这个程序。额外的加分:也加入除法;这比较难做因为你要找到有效的整形除数,幸运的是,已经有代码来确定分子比分母大,所以不需要支持分数。
【答案】
添加了乘法后,代码如下:

#-*- encoding: utf-8 -*-
# easyMath.py

from operator import add, sub, mul
from random import randint, choice

ops = {'+': add, '-': sub, '*': mul}

MAXTRIES = 2

def doprob():
    op = choice('+-*')
    nums = [randint(1, 10) for i in range(2)]
    nums.sort(reverse = True)
    ans = ops[op](*nums)
    pr = '%d %s %d = ' % (nums[0], op, nums[1])
    oops = 0
    while True:
        try:
            if int(raw_input(pr)) == ans:
                print 'Correct!'
                break
            if oops == MAXTRIES:
                print 'Answer\n%s%d' % (pr, ans)
            else:
                print 'Incurrect... try again'
                oops += 1
        except (KeyboardInterrupt, EOFError, ValueError):
            print 'Invalid input... try again'
            
def main():
    while True:
        doprob()
        try:
            opt = raw_input('Again? [y]').lower()
            if opt and opt[0] == 'n':
                break
        except (KeyboardInterrupt, EOFError):
            break
    
if __name__ == '__main__':
    main()
            


添加了除法后,代码如下:

#-*- encoding: utf-8 -*-
# easyMath.py

from operator import add, sub, mul, div
from random import randint, choice

ops = {'+': add, '-': sub, '*': mul, '/': div}
# From www.cnblogs.com/balian/

MAXTRIES = 2

def doprob():
    op = choice('+-*/')
    nums = [randint(1, 10) for i in range(2)]
    nums.sort(reverse = True)
    if op != '/':
        ans = ops[op](*nums)
        pr = '%d %s %d = ' % (nums[0], op, nums[1])
    else:
        ans = div(nums[0], nums[1])
        if div(nums[0] * 10, nums[1]) == ans * 10: # 这里用来判断是否能整除
            pr = '%d %s %d = ' % (nums[0], op, nums[1])
        else:
            ans = mul(nums[0], nums[1]) # 如果不能整除的话,将运算符修改成乘法
            pr = '%d %s %d = ' % (nums[0], '*', nums[1])
    oops = 0
    while True:
        try:
            if int(raw_input(pr)) == ans:
                print 'Correct!'
                break
            if oops == MAXTRIES:
                print 'Answer\n%s%d' % (pr, ans)
            else:
                print 'Incurrect... try again'
                oops += 1
        except (KeyboardInterrupt, EOFError, ValueError):
            print 'Invalid input... try again'
            
def main():
    while True:
        doprob()
        try:
            opt = raw_input('Again? [y]').lower()
            if opt and opt[0] == 'n':
                break
        except (KeyboardInterrupt, EOFError):
            break

# From www.cnblogs.com/balian/    
if __name__ == '__main__':
    main()
 

 

11-17.定义
(a)描述偏函数应用和currying之间的区别。
(b)偏函数应用和闭包之间有什么区别?
(c)最后,迭代器和生成器是怎么区别开的?
【未完】
感觉本题要说清楚有点难度,暂时押后。