11.11 Practice

Source: Internet
Author: User
Tags parent directory string format

11–1. Parameters. Compare the following 3 functions:

Def countToFour1 ():
    for Eachnum in range (5):
        print Eachnum,
def COUNTTOFOUR2 (n): for
    eachnum in range (n , 5):
        print Eachnum,
def countToFour3 (n=1): for
    eachnum in range (n, 5):
        print Eachnum,

Given the following input until the program output, you know why it happened. Table 11.2 below fills in the output. If you think that the given input will be wrong, fill in "error" or, if there is no output, fill in "None"
11-2. function. Combine your solution for exercise 5-2 so that you can create a binding function with the same pair of numbers and return both their sum and the product.
Table 11.2 Output diagram of question 11-1

Input      countToFour1      countToFour2     countToFour3

2          ERROR             2 3 4            2          3 4 4 Error             4                4

5          error             none             none

(Nothing)  0 1         2 3 4 ERROR            

11-3 function. In this exercise, we will implement the Max () and Min () built-in functions.
(a) write with two elements to return a larger and smaller element, simple max2 () kernel min2 () function. They should be able to work with any Python object. For example, Max2 (4,8) and min2 (4,8) each return 8 and 4 each time.

def max2 (a,b):
    max_num = a
    if a<b:
        max_num =b return
    max_num
def min2 (a,b):
    min_num = a
    If a>b:
        min_num =b return
    min_num

(b) Create a new function My_max () and My_min () using the Che Lai refactoring Max () and Min () in part A. These functions return one of the largest and smallest values in non-null queues, respectively. They can also take a set of parameters as input. Use numbers and strings to test your solution.

I understand the problem, and the online code is not the same
def max2 (a,b):
    max_num = a
    if a<b:
        max_num =b return
    max_num
Aset={1}
My_max = reduce (max2,aset)
print My_max

11–4. The return value. Create a supplemental function for your solution in 5-13. Create a total time band to divide into units and return an equivalent total time in hours and in units.

#5-13 input is not the hour and divided into units. The title is not clear
. Def change_time ():
    time=raw_input ("Input a Time split by":   ")
    minutes =int (time.split (': ') ) [0]) *60 +int (Time.split (': ') [1])
    print time, "is Equl", minutes, "minutes"
change_time ()

11–5. Default parameters. Update the sales tax script that you created in exercise 5-7 so that the sales tax rate is no longer necessary for function input. Create a default parameter that uses your local tax rate if no value is passed in at the time of the call.

Def tax (money,tax_ratio=0.6):
    tax=money*tax_ratio return
    tax

11–6. Variable length parameters. The next function called printf (). Has a value parameter, a format string. The rest is based on the values on the formatted string, the variable parameters to display on the standard output, the values in the formatted string allow for special string format operation indicators, such as%d,%f, etc. Hint: The solution is trivial-no need to implement string operator functionality, but you need to display a string format operation (%)

#抄网上代码
def printf (rule,*num):
    i =-1 for
    J in num:
        i = rule.find ("%", i+1)  #对% positioning, discussed and replaced
        in three different scenarios If rule[i+1]== "D" and type (j) ==int: Result
            = Rule.replace ("%d", str (j), 1)
        elif rule[i+1]== "F" and type (j) = = float: Result
            = Rule.replace ("%f", str (j), 1)
        elif rule[i+1]== "s" and type (j) ==str: Result
            = Rule.replace ("%s", j,1)
        else:
             print  "ERROR"  #当对应类型不正确时抛出异常
             exit (0) Rule
        = result
    Print Result

11–7. Use map () for functional programming. Given a pair of the same size list, such as [1,2, 3] and [' ABC ', ' Def ', ' Ghi ',....], merge two marks into a single table of tuples of each list element to make our results look like this: {[(1, ' abc '], (2, ' Def '), (3, ' Ghi '), ...}. (Although the problem is essentially similar to a problem in chapter sixth where two solutions are not directly connected) then create another solution with a zip built-in function.

A=[1, 2, 3,]
b=[' abc ', ' Def ', ' Ghi ']
map (none,a,b)

a=[1, 2, 3,]
b=[' abc ', ' Def ', ' ghi ']
zip (a,b)

11–8. Use filer () for functional programming. Using exercise 5-4 you give the code to determine the year. Update your code side he becomes a function if you haven't done that yet. Then write a piece of code to give a list of the year and return a list of only leap years. Then turn it into a list resolution.

Def judge_year (year):
    if (year%4==0 and year%100!=0) or year%400 ==0: return
        True
    else: return
        False

Year_list=range (1987,2020)
leap_year=filter (judge_year,year_list)
print leap_year
#列表解析 [year to year in    
range (1987,2020) if (year%4==0 and year%100!=0) or year%400 ==0]

11–9. Use reduce () for functional programming. Review the 11.7.2 section to illustrate how to use the cumulative code of the reduce () number set. Modify it to create a function called average () to compute the simple average of each set of numbers.

Average = reduce (lambda x,y:x+y,range ())/float (Len (range (10))

11–10. Use filter () for functional programming. In the Unix file system, there are two special files in each folder or directory: '. ' The current directory, ' ... ' Represents the parent directory. Given the above knowledge, look at the documentation of the Os.listdir () function and describe what this code does:
Files = Filter (lambda x:x and x[0]!= '. ', OS. Listdir (folder))

#不懂

11–11. Use map () for functional programming. Write a "clean" file by using the filename and by dropping all the top and end blanks in each row. Read in the original file and write to a new file, create a new one, or overwrite the existing one. Give your users a choice to decide which to perform. Convert your solution to use list resolution.

 #抄的网上代码 def strip (strtemp): Return Strtemp.strip () while true:filename = Raw_input ("Plea Se enter the fileName (Q to Quit): ") if filename.lower () = =" Q ": Break choice = Raw_input (" N to new file, O
        R c to cover file: ") if choice.lower () = =" N ": NewFileName = raw_input (" Please enter the new file name: ") With open (NewFileName, "w") as Fobj:with Open (fileName) as Fobjold:lines = Fobjold.readli NES () for line in map (strip, lines): Fobj.write (repr (line)) FOBJ.W Rite ("\ n") Else:with open (fileName) as Fobjold:lines = Fobjold.readlines () with Open (fil
                ename, "W") as Fobjold:for line in map (strip, lines): Fobjold.write (repr (line)) Fobjold.write ("\ n") 

11–12. Transfer function. Write a sister function for the testit () function described in this chapter. Timeit () Takes a function object (along with the parameters) and calculates how long it takes to execute the function, not the error of the test execution. Returns the following status: function return value, time consumed. You can use Time.clock () or time.time (), whichever one gives you a higher degree of precision. (The general consensus is to use Time.time () on POSIX, using Time.clock () on the Win32 system)
Note: the Timeit () function is not related to the Timeit module (introduced in python2.3)

Import Time
def Timeit (func):
    start_time = time.clock () result
    = Func End_time
    = Time.clock ()
    Return (result, End_time-start_time)

def func (A, B): Return
    A * b

print Timeit (func (23, 12))

11–13. Use reduce () for functional programming and recursion. In the 8th, we see the factorial or n! of N as the product of all numbers from 1 to N.
(a) A simple and compact function that writes a minute with X,y and returns their product named Mult (x,y).

def mult (x,y): Return
    X*y

(b) Use the mult () function you created in a and reduce to compute the factorial.

def mult (x,y): Return
    x*y
def fac1 (n): return
    reduce (mult, range (1,n+1))

(c) Completely discard the use of mult () and replace it with an LAMDA expression.

def FAC2 (n): Return to
    reduce (lambda x, y:x * y, Range (1,n+1))

(d) In this chapter, we describe a recursive solution to find n! the Timeit () function you completed in the above question and to time the three-version factorial function (iteration, reduce (), and recursion)

#暂空

11–14. Recursion. We will also look at the Fibonacci figures in chapter eighth. Rewrite the solution of your previous calculation of the Fibonacci number (exercise 8-9) so that you can use recursion.

def Fibo (n):
    If n = 1: return
        1
    elif n = 2: return
        1
    else: return
        Fibo (n-1) + Fibo (n-2)

11–15. Recursion. From the solution of writing exercise 6-5, print a string backwards with recursion. Prints a string with recursion forward and backwards.

#抄网上代码
#向后打印
def printleft (strtemp):
    if strtemp:
        print strtemp[0], return
        printleft (strtemp[ 1:]
#向前打印
def printright (strtemp):
    if strtemp:
        print strtemp[-1], return
        printright ( STRTEMP[:-1])

11–16. Update easymath.py. This script, as illustrated in Example 11.1, is an introductory program to help young people strengthen their math skills. This program can be further upgraded by adding multiplication as a supported operation. Extra points: Also add division; it's harder to do because you have to find a valid integer divisor. Fortunately, there is already code to determine the molecular score of the parent, so there is no need to support fractions.

# Too much trouble, big head ...

11–17. Definition
(a) Describe the difference between the application of the partial function and the currying.
(b) What is the difference between the application of the partial function and the closure.
(c) Finally, how the iterator and generator are distinguished.

#没什么深入的理解, let go.

11–18. A synchronization function call. Review the husband and wife situations mentioned in the sixth chapter when introducing shallow copies and deep copies (6.20 summaries). They shared a common account and had a negative impact on their bank account visits.

Create a program that allows calls to change the balance of accounts must be synchronized. In other words, there can be only one process or thread at any given time to execute a function. At first you try to use files, but a real solution is to use adorners and synchronization instructions in threading or mutex modules. You see the 17th ticket get more inspiration.

No

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.