Python is encapsulated into a dictionarydefFun_test6 (a,**Kvavgs):Print(a)Print(Kvavgs) Fun_test6 ("a", x="b", y="C", z="D")#Multiple return Valuesdeffun_test7 ():return0,"a",("b","C"),["D","e","e"],{"F","g"},{"name":"Zhang"," Age": 20}res=fun_test7 ()#This returns the returned result into a tuplePrint(RES)#recursive functions that function themselves to call themselves#recursive functions must have a few three special: 1. There are definite end cond
fib (A1,A2): # print A1,A2, a3=a1+a2 if a3>100: #这里加入了结束条件, if not, will form a dead loop return A3 # Print a 3, return fib (A2,A3) # fib (a2,a3) print fib (0,1)Recursion can be converted to and from while.The code in the above code is implemented with a while loop:A1,A2 = 0,1While a1Print A1A2=a1+a2A1=a2-a1http://timesnotes.blog.51cto.com/1079212/1716574http://www.timesnotes.com/?p=114This article is from the "'ll Notes" blog, so be sure to keep thi
This example describes Python's approach to solving the eight Queen problem based on right recursion. Share to everyone for your reference. The specific analysis is as follows:
All linear backtracking can be attributed to the form of right recursion, that is, two-fork tree, so for a problem that only requires a solution, the right recursive implementation of the program is more beautiful than the backtrac
* (2 * 1))) ===> 5 * (4 * (3 * 2)) ===> 5 * (4 * 6) ===> 5 * ===> + Recursive functions have the advantage of simple definition and clear logic. In theory, all recursive functions can be written in a circular way, but the logic of the loop is not as clear as recursion. The uses recursive functions that require attention to prevent stack overflow. In the computer, the function call is implemented through a stack (stack) of this data structure, e
backward forward in the sequence of elements that are already sorted 3. If the element (sorted) is greater than the new element, move the element to the next position 4. Repeat step 3 until you find that the sorted element is less than or equal to the new element's position 5. After inserting a new element into the location m = [1,4,6,2,5] for in range (1, Len (m)): = M[i] = I while and m[j-1]>Save: = m[j-1] J-=1 = Save Print (m)-Attached: A method for taking
The so-called palindrome string, that is, a string from left to right reading and right-to-left reading is exactly the same. For example: "Level", "aaabbaaa", "Madam", "radar".How can I tell if a string is a palindrome? The solution is as follows:1. Take the exhaustive method (Brute force algorithm), enumerate and check (enumerate check) whether the first and last items of a string are equivalent2. Gradually reduce the scope of the check, if the first and last item of the string is equal, then
'name': i[0],7 'Sex': i[1],8 ' Age': Int (i[2]),9 'Salary': Int (i[3])Ten } One data.append (DIC) A - #[{' Name ': ' Egon ', ' sex ': ' Male ', ' age ': ' Salary ' : - #{' name ': ' Alex ', ' sex ': ' Male ', ' age ': $, ' salary ': 30000}, \ the #{' name ': ' Wupeiqi ', ' sex ': ' Female ', ' age ': +, ' salary ': 20000},\ - #{' name ': ' Yuanhao ', ' sex ': ' Female ', ' age ': +, ' salary ': 10000}] - -Res=max (data,key=Lambdax:x['Sal
)If we calculate func (5), you can see the calculation process as follows from the function definition:===> func (5)===> 5 * func (4)===> 5 * (4 * func (3))===> 5 * (4 * (3 * func (2)))===> 5 * (4 * (3 * (2 * func (1)))===> 5 * (4 * (3 * (2 * 1)))===> 5 * (4 * (3 * 2))===> 5 * (4 * 6)===> 5 * 24===> 120The advantage of recursive functions is that they are simple in definition and clear in logic. In theory, all recursive functions can be written in a circular way, but the logic of the loop is not
Go back in the evening to review the original information, return to the codebook there is a "expand a nested Sequence" topic.Task description: The child in the sequence may be a sequence, the child of the subsequence may still be a sequence, and so on, the sequence nesting can reach any depth. You need to loop through a sequence and expand all of its subsequence into a single sequence with only the basic subkeys.For example, the shape is the following sequence a: a = [(123 (78)]" , 45, 69, 10
Recursive
Invoking the behavior of the function itself
Have a correct return condition
def factorial (n):if n = = 1:Return 1Elsereturn n * Factorial (n-1)Number = Int (input (' Please enter a positive integer: '))result = factorial (number)Print (' Factorial of '%d:%d '% (Number,result))def Hanoi (n, x, Y, z):if n = = 1:Print (x, '---', z)ElseHanoi (n-1, X, Z, y) #将前n-1 plates moved from X to YPrint (x, '---', z) #将最底下的最后一个盘子从x移动到z上Hanoi (n-1, y, X, z) #将y上的n-1 plates move to Z
The first method: recursion
Copy Code code as follows:
def perms (elements):
If Len (elements) Yield elements
Else
For Perm in Perms (elements[1:]):
For I in range (len (elements)):
Yield perm[:i] + elements[0:1] + perm[i:]
For item in list (perms [1, 2, 3,4]):Print Item
Results
Copy Code code as follows:
[1, 2, 3, 4]
[2, 1, 3, 4]
[2, 3, 1, 4]
[2, 3, 4, 1]
[1, 3, 2, 4]
[3, 1, 2, 4]
[3, 2,
sequenceCombined with a functionCombined with LambdaFilter ()Filter functions:Syntax: Filter (function. iterable) function : functions used for filtering, in the filter will be automatic bar iterable elements in the pass to function, and then according to function returns TRUE or FALSE to determine whether to preserve this data iterable: an Iterative objectMap ()Mapping functions:Syntax: Map (function,iterable) can map each element in an iterative object, taking an execution functionCalculates
internallyCharacteristics:There must be a definite end condition, no end condition will result in exceeding the maximum number of recursive layers (English) error, maximum 999 levelsEvery step deeper, the problem should be less than it was last time.Inefficient, function is called by the stack, may cause stack OverflowIn Python, division by default can be the result of a decimal, and if you want to take an integer, truncate (//) with an int (1/2). )R
threading Import Threadimport timedef Work (): res = 0 for i in range (10000000): res+=iif __name__ = = ' __main__ ': l = [] Start = Time.time () for I in range (4): P = Process (target=work) #1.9371106624603271 #可以利用多核 (i.e. multiple CPUs) # p = Thread (target=work) #3.0401737689971924 l.append (P) p.start () for P in L:p.join () stop = Time.time () print ('%s '% (Stop-start)) # I/O intensive to turn on multithreading from multiprocessing import processfrom threading Import Threadimport ti
scientific notation), and format it to a specified position (if the scientific count is e;)-%, when there is a format flag in the string, you need to use the Percent percent represents a semicolon Note: There is no way to automatically convert an integer to a binary representation in Python with a percent-semicolon formatPractice:TPL = "I am%s"% "Alex" Print (TPL) TPL = "I am%s age%d"% ("Alex", page) print (TPL) TPL = "I am% (name)" s age% (age) d "
the stop iteration. In Python, many objects can be traversed directly through a for statement, such as list, String, Dict, and so on, which can be called an iterative object. As for which objects can be accessed iteratively, it is necessary to understand the knowledge of iterators.IteratorsThe iterator object requires an object that supports the iterator protocol, in Python, the __iter__ () and Next () met
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.