4. built-in functions, file operations and recursion, and function Recursion

Source: Internet
Author: User
Tags decimal to binary

4. built-in functions, file operations and recursion, and function Recursion
I. built-in functions

There are many built-in functions in Python. The following figure lists all the built-in functions. Then, I will explain some common functions. I can refer to the following code for better understanding.

# Anonymous Functions f = lambda a, B: a + bprint (f (2, 3) #5 # abs () take absolute value print (abs (-111 )) #111 # all () loop returns True if every element of the iteratable object is True. Otherwise, false #0, None, "", [], (), {} is a false print (all ([]) # True # One of any is True, all are True print (any ([, None]) # False # Find _ repr __in the object class in ascii, and obtain the returned class D (): def _ repr _ (self): return 'hello' d = D () print (ascii (d) # hello # bin convert decimal to binary # oct () hex () print (bin (11 )) #0b1011 # convert various hexadecimal values to decimal values using int () print (int ('11', base = 2 )) # convert the binary '11' to the decimal number 3 # bytearry byte list # chr () Find the ascii code for the number # ord () number corresponding to the ascii code # chr ord only applies to the ascii code print (chr (65) # Aprint (ord ('A ')) #65 # Check whether the callable string can be executed by adding parentheses # complie () to accept a string and convert it into function code # divmod returns the Division (value, remainder) print (divmod () # eval calculator function returned result print (eval ('a + 60', {'A': 90 })) #150 print (eval ('3 + 4*6/7 + (1 + 2)-5) ') #4.428571428571429 # exec, execute python code, no return value exec ("for I in range (5): print (I)") # directly loop the output 0, 1, 2, 3, 4 # filter (function, iteratable object) # The objects that can be iterated in a loop are passed into the function for execution. if they do not match, the def fun (s): # define a function that determines whether a number is an even number if s % 2 = 0: return True else: return Falseret = filter (fun, [,]) for I in ret: print (I) # print out 2, 4, 6, 8 # rewrite ret1 = filter with an anonymous function (lambda x: x % 2 = 0, [,]) for I in ret1: print (I) #2, 4, 6, 8 # map sequentially applies the input function to each element of the sequence, and uses the result as the new Iterator to return ret = map (lambda x: x + 100, 3]) for I in ret: print (I) #101,102,103 # globals () Get all global variables of the current file # locals () Get all local variables of the current file # hash () obtain the hash value # isinstance to check whether an object is created by a class # iter () creates an object that can be iterated next () and obtains the next value k = iter ([1, 2, 4]) print (next (k) #1 # pow () Evaluate the index print (pow (1024) # round () Rounding # zipl1 =, 3, 4] l2 = ['A', 'B', 'C', 'D'] k = zip (l1, l2) for I in k: print (I) # print (1, a), (2, B )....
Ii. File Operations

File Operations are divided into three processes: Opening a file, operating a file, and closing a file. However, it is very troublesome to close the file every time, and you may forget to close the file during actual operations, so we use another operation and the with statement, so that we do not need to manually close the file. In subsequent operations, I will use the with method to open the file.

Comment ', 'R', encoding = 'utf-8') # open the file data = f. read () # operation file f. close () # close the file print (data) # Use the with statement to open the file. You do not need to automatically close with open('1.txt ', 'R', encoding = 'utf-8') as f: print (f. read ())

The following methods are used to open a file:

  • R, read-only mode [Default]
  • W, write-only mode [unreadable: The content is created if it does not exist; the content is cleared if it exists ;]
  • X: Write-only mode. [unreadable: If the input parameter does not exist, it is created. If the input parameter exists, an error is returned]
  • A. append mode: [unreadable; created if no content exists; only content is appended if yes ;]

"+" Indicates that a file can be read and written simultaneously, such as r +, w +, x +, and a +. "B" indicates that rb, r + B, wb, w + B, xb, x + B, AB, or a + B are operated in bytes, the read content is of the byte type. You also need to provide the byte type when writing data. All of these must be converted by the programmer. The following code is used to perform the conversion.

With open('1.txt ', 'R', encoding = 'utf-8') as f: print (f. read () # 1.txt, No, Error # w write only (not readable, not created, empty if yes) with open('1.txt ', 'w') as f: f. write ('000000') Create 1.txt write new content 888 # x write only (unreadable, not created, error reported) with open('1.txt ', 'x') as f: f. write ('000000') # Here, Error # a append mode (unreadable, not created, append to end) with open('1.txt ', 'A') as f: f. write ('000000') into 1.txt and append 777' in the format of a slash to empty the file content in 1.txt, and write the 'string' into it # manually convert with open('1.txt ', 'wb') as f: str_data = 'string' byte_data = bytes (str_data, encoding = 'utf-8') f. write (byte_data) # Read with rb open('1.txt ', 'rb') as f: data = f. read () print (type (data) # print the read type byte str_data = str (data, encoding = 'utf-8') # convert byte to string print (str_data) # print the 'string'

The following describes how to use "+" to read and write a file at the same time.

# Append the pointer to the end when writing in the r + format. # You must be clear about the position pointed by the pointer when reading and writing. The following example must be clear: # f. location where tell () reads the pointer # f. seek (0) sets the pointer position with open('1.txt ', 'r +', encoding = 'utf-8') as f: print (f. tell () # print the position of the pointer when the file starts to point to 0 print (f. read () # read the 'string', print (f. tell () # The file pointer refers to 9, a man has three strings, and the pointer is in character units f. write ('corby') # write content 'corby'. Note that at this time, the file refers to print (f. read () # The pointer goes to the end, so the read content is null print (f. tell () # pointer to 15 f. seek (0) # point the pointer content to 0 position print (f. read () # because the file Pointer Points to the beginning, you can read the content string Kobe # w + if the format exists, first clear the pointer when writing to the end with open('1.txt ', 'W + ') as f: f. write ('kg ') has 1.txt, so clear the content, and then write 'kg' print (f. tell () # The Pointer Points to 2 print (f. read () # The content cannot be read because the Pointer Points to the end of f. seek (0) print (f. read () # read the content, because the pointer has been restored to the starting position # When a + is opened, the pointer has been moved to the end, so we will not demonstrate it here, if the # x + file already exists, you can try it yourself.

Suppose there is such a requirement that there is a 10 Gb file, how to copy it to another file? The following describes how to open two files at the same time for processing, and how to read the files when the files are too large. You can use the with statement to open two files at the same time, one read and one write. Assume that the 1.txt file is 10 Gb in size. If read is used, the content will be read to the memory at one time. This is obviously not suitable. If readline () is used, you can also read a row, but I don't know when it will end, but I can use the for loop to read the file, the iteratable object, and read a row. The following three lines of code can be implemented:

With open('1.txt ', 'R', encoding = 'utf-8') as fread,open('2.txt', 'w') as fwrite: for line in fread: # fwrite for a row. write (line) # write a row
Iii. Recursion

If a function calls itself internally, it is called recursion, but a condition for exit recursion should be set during recursion. Otherwise, it will always go recursive and become an endless loop. On the other hand, recursion is actually equivalent to loop. If we want to understand recursion, we will first illustrate this point from the actual example. For example, if we want to write a factorial function f (n) to calculate the factorial of n, there are many ways to implement the factorial function, the following describes how to implement it using recursion.

Def f (n): if 0 = n: # if n = 0, null is directly returned. return None elif 1 = n: # If n = 1, return n else: return n * f (n-1) # Recursive Execution of f (n-1) direct channel f (1) print (f (5 )) #120 ''' f (5) Execution Process: ==> f (5) ==> 5 * f (4) ==> 5*(4 * f (3) ==> 5*(4*(3 * f (2 ))) ==> 5*(4*(3*(2 * f (1 )))) ==> 5*(4*(3 * (2*1) ==> 5*(4*(3*2 )) => 5 * (4*6) => 5*24 => 120 '''

The last essay in the previous article is to use recursion to obtain the number of 10th in the Fibonacci series. Here we are going to explain how to implement it. the Fibonacci series starts from, the Fibonacci coefficient is the sum of the previous two numbers. Let's look at the code first,

Def fun (n): # fun (10) is used to calculate the Tenth Fibonacci number. if 1 = n: # define the first two numbers as 0, 1, if the input n is 1, 2, return the return 0 elif 2 = n: return 1 else: return fun (n-1) + fun (n-2) # If the input is not 1 or 2, recursively calculate the execution process of the two preceding and '''fun (5) as follows ==> fun (5) ==> fun (4) + fun (3) ==> fun (3) + fun (2) + fun (2) + fun (1) ==> fun (2) + fun (1) + fun (2) + fun (2) + fun (1) ==> 1 + 0 + 1 + 1 + 1 + 0 ==> 3 '''
Iv. Exercises

Use the built-in functions chr (), ord (), and random to write a simple random 4-digit verification code.

Import randomtmp = ''# The Last generated random code for I in range (4): n = random. randrange () # generate a random number 1 or 0 to determine whether the following is a random number or the letter if n = 0: num = random. randrange (65, 91) # when it is 0, the uppercase letter tmp + = chr (num) else: k = random is generated. randrange () # when it is 1, generate the number tmp + = str (k) print (tmp) # Here the 4 generated each time during running is different from the random code

  

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.