The answer in this blog is not from official resources, but from my own exercises. If you have any questions or errors, please discuss them.
11-12.
Transfer functions. Write a sister function for the testit () function described in this chapter. Timeit () carries a function object (with parameters) and calculates the amount of time it takes to execute the function, rather than the error during testing. Return the following status: function return value, time consumed. This article is from the blog. You can use time. clock () or time. time (), no matter which one gives you a higher accuracy (the general consensus is that time is used on POSIX. time (), which is used on win32 systems. clock ()). Note: The timeit () function is irrelevant to the module timeit (introduced in python2.3 ).
[Answer]
The Code is as follows:
import timedef timeit(func): start_time = time.clock() result = func end_time = time.clock() return (result, end_time - start_time)def func(a,b): return a - bprint timeit(func(2,1))
11-13.
Use reduce () for functional programming and recursion. In chapter 2, we can see that the factorial of N or N is the product of all numbers from 1 to N.
(A) write a simple and compact function with x and y in one minute and return their product name mult (x, y.
(B) Use the mult () function you created in (a) and reduce to calculate the factorial.
(C) discard the use of mult () and use lamda expressions instead.
(D) In this chapter, we depict a recursive solution to find N! Use the timeit () function that you have completed in the preceding problem, and time the three version factorial functions (iterative, reduce () and Recursion ).
[Answer]
(A) The Code is as follows:
>>> def mult(x,y):... return x * y...>>> mult(2,3)6>>>
(B) The Code is as follows:
>>> def factorial(n):... return reduce(mult, range(n+1)[1:])...>>> factorial(6)720>>>
(C) The Code is as follows:
>>> def factorial(n):... return reduce((lambda x,y: x*y), range(n+1)[1:])...>>> factorial(6)720
(D) The Code is as follows:
# From www.cnblogs.com/balian/developer-*-encoding: UTF-8-*-import timedef timeit (func): "Timing function" start_time = time. clock () result = func end_time = time. clock () return (result, end_time-start_time) def factorial_iteration (n): "Use cyclic calculation factorial" result = 1 for eachItem in range (n + 1) [1:]: result = result * eachItem return resultdef factorial_lambda (n): "calculate a factorial using lambda" return reduce (lambda x, y: x * y), range (n + 1) [1:]) def factorial_recursion (n): "use recursion to calculate factorial" if n = 0 or n = 1: return 1 else: return (n * factorial_recursion (n-1) number = 6 print "use cyclic calculation factorial:" print timeit (factorial_iteration (number), '\ n' print "use lambda: "print timeit (factorial_lambda (number), '\ n' print" use recursion: "print timeit (factorial_recursion (number),' \ N'
Key words: Python core programming answers