1. Functions
Function, including the following three aspects
Modular
Ignore details
Create a new beginning
What is a new beginning? For example, if the square root of a number is computed and abstracted and represented by a function, the square root is a new basic consideration. The following describes how to implement this process. First, let's take a look at the code written to calculate the square root:
# Find the square root of a perfect square 2.0x = 16ans = 0if x>=0: while ans*ans <x: ans = ans + 1 print('ans =',ans) if ans*ans != x: print(x,'is not a perfect square') else: print(ans)else: print(x, 'is a negative number')
Our goal is to abstract it, just like a black box. You only need to enter a number to get the result. When using functions, there are several basic elements:
Def-define the function keyword
Name (x)-name of the function, followed by x as a form parameter, can be understood as a virtual variable
Return-return Value
You only need to modify it a little.
Def sqrt (x ):
'''
Ans = 0 if x> = 0: while ans * ans <x: ans = ans + 1 if ans * ans! = X: print (x, 'is not a pefect square') return None else: return ans else: print (x, 'is a negative number') return None
None is a special return value. Although None is returned, no information is displayed on the screen.
# Recognize returned values Nonetest = sqrt (3) test # => No information is printed test = None #= truetype (test) #=> <class 'nonetype '>
2. Local variables and global variables
For the sqrt () We created, the call is very simple, such as sqrt (16). At this time, we will talk about allocating 16 to x. Note that x here refers to a local variable, that is, x only acts in this function.
The value of the local variable does not affect the global variable.
We can understand it through a simple example. First, we define the function f (x). The function is to add the value of x to 1.
def f(x): x=x+1 return xx=3z = f(x) print(x) #=》3print(z) #=》4
Although the x in the f function is changed to 4 during z = f (x), the final value of x is still 3. Because x in function f is a local variable.
3. Solve the Problem of coquy cages
Example 1: pigs and chickens have a total of 20 heads and 56 feet.
We can consider traversing the number of pig to solve the problem.
Def solve1 (heads, legs): ''' the total number of pigs and chickens and total number of legs are given, and the number of pigs and chickens is returned ''' in range (0, heads + 1): chicks = heads-pigs piglegs = pigs * 4 chicklegs = chicks * 2 if (piglegs + chicklegs) = legs: return (pigs, chicks) return (None, none)
Example 2: know the total number of pigs, chickens, and spider, and the total number of legs.
Nested training can be used for implementation.
def solve2(numLegs, numHeads): '''return the number of pigs,chicks and spiders''' for numSpiders in range(0, numHeads + 1): for numChicks in range(0, numHeads - numSpiders + 1): numPigs = numHeads - numChicks - numSpiders totLegs = 4*numPigs + 2*numChicks + 8*numSpiders if totLegs == numLegs: return (numPigs, numChicks, numSpiders) return (None, None, None)
However, this function returns only one result. In fact, the number of three is not necessarily unique. If you want to output all the results, it is actually very simple, just print it out.
# Out all possible results def solve3 (numLegs, numHeads): solutionFound = False for numSpiders in range (0, numHeads + 1 ): for numChicks in range (0, numHeads-numSpiders + 1): numpig = numHeads-numChicks-numSpiders totLegs = 4 * numPigs + 2 * numChicks + 8 * numSpiders if totLegs = numLegs: print ('number of pigs: '+ str (numpig) +', ') print ('number of chicken:' + str (numChicks) + ',') print ('number of spiders: ', numSpiders) solutionFound = True if not solutionFound: print ('there is no solution. ')
A boolean variable solutionFound is set here to determine whether a qualified result exists. not solutionFound means that if solutionFound = False, then true
4. Recursion
American Law defines Americans as follows:
If you were born in the United States, you are an American.
If you were born outside of the United States, as long as your parents are American and one of them lives in the United States, you are still American.
This is actually a recursive definition, because how do you know whether your parents are American? We also need to continue tracing, even to Adam and Eve.
The basic idea of recursion is to break down the problem into simpler problems that can be solved.
Back-to-text: string with the same read from left and read from right
Next, we can determine whether a string belongs to the background. It is very troublesome to consider other methods, but it is really easy to do it using recursion.
First, recursively define the input:
If the string does not contain any elements, the string is a background;
If the string contains an element, the string is a forward object;
In other cases, determine whether the first two characters are equal. If they are equal, remove the first two characters and repeat the results.
The code implementation is as follows:
# Use recursion to determine whether the string belongs to the background def isPalindrome (s): if len (s) <= 1: return True else: return s [0] = s [-1] and isPalindrome (s [1:-1])
First, make a judgment. If the length is 0 or 1 (that is, it does not contain any element or only contains one element), it is a string;
Otherwise, determine whether the first two characters are equal. s [0] indicates the first character, and s [-1] indicates the last character. If the two characters are equal, remove the first character (s [1: -1]), and then repeat the judgment.