本部落格列出的答案不是來自官方資源,是我自己做的練習,如果有疑問或者錯誤,歡迎討論。
11-16.
更新easyMath.py。這個指令碼,如例子11.1描繪的那樣,以入門程式來協助年輕人強化他們的數學技能。通過加入乘法作為可支援的操作來更進一步提升這個程式。額外的加分:也加入除法;這比較難做因為你要找到有效整形除數,幸運的是,已經有代碼來確定分子比分母大,所以不需要支援分數。
【答案】
添加了乘法後,代碼如下:
#-*- encoding: utf-8 -*-# easyMath.pyfrom operator import add, sub, mulfrom random import randint, choiceops = {'+': add, '-': sub, '*': mul}MAXTRIES = 2def 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.pyfrom operator import add, sub, mul, divfrom random import randint, choiceops = {'+': add, '-': sub, '*': mul, '/': div}# From www.cnblogs.com/balian/MAXTRIES = 2def 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)最後,迭代器和產生器是怎麼區別開的?
【未完】
感覺本題要說清楚有點難度,暫時押後。