[Python]---- Python's functions and recursion

function 1. Use of functions in Python Benefits of using functions: 1. Avoid code redundancy 2. Make the program code st...
function
System Higher Order Functions
recursion
Practice

function

1. Use of functions in Python
Benefits of using functions:
1. Avoid code redundancy
2. Make the program code structure clearer
3. Make code reusable and easy to maintain
Format of function definition:

def function name (parameter list): Function Body
# 1. Write the simplest function def sayHello(): print('hello') # Call function sayHello() # 2. Functions with parameters def sayHello2(name): print('Hello', name) sayHello2('Beijing') # 3. Functions with Return Values # 1 Add up to any integer def caculateNum(num): # Storage cumulative sum sumNum = 0 for i in range(1, num+1): sumNum = sumNum + i # Return sumNum return sumNum res = caculateNum(100) print(res)

Use assertions in functions
Format: assert expression [, parameters]
When the expression is false, throw an AssertionError error and output the parameter

def div(s): # Convert to Integer n = int(s) # Determine if the parameter passed in is valid and the expression is true before executing down assert n != 0, 'n is zero' return 10/n print(div('0'))

2. Anonymous functions
1. The keyword lambda denotes an anonymous function, and n preceded by a colon denotes a function parameter, which can have multiple parameters.
2. Anonymous functions have a limitation that there can only be one expression, and the return value is the result of that expression without writing return.
3. The advantage of using anonymous functions is that they do not have names and there is no need to worry about conflicting function names.In addition, an anonymous function is also a function object, you can assign an anonymous function to a variable, and then use the variable to call the function: some functions are used only once in the code, and the body of the function is simpler, using anonymous functions can reduce the amount of code, it looks more "elegant".

# Anonymous function # lambda parameter_list: expression # There is no limit to the number of parameter lists, but expressions can only have one cal = lambda x, y: x*y print(cal(2, 3)) def calc(x, y): if x >= y: return x/y else: return x*y print(calc(4, 2)) # Using the above code as an anonymous function # Ternary expression # Content returned when True if True condition else False calc2 = lambda x, y: x/y if x >= y else x*y print(calc2(4, 2))

System Higher Order Functions

1. map() function
map(func, iterable) passes Iterable objects to the func process in turn, and returns the result as a new Iterable object

# map() function def power(x): return x*x # Function name passed res = map(power, [1, 2, 3, 4, 5]) # res returns a generator print(list(res)) # [1, 4, 9, 16, 25] # Using lambda expressions print(list(map(lambda x: x*x, [1, 2, 3, 4, 5])))

2. reduce() function
reduce(func, iterable) function: Cumulative operation.The func function must accept two parameters, reduce takes the result of the func as one parameter, and then takes one data from the Iterable as another parameter in turn.

# reduce function # Reduc is no longer in build-in function after python 3.0. To use it you have to import reduce from functools from functools import reduce li = [1, 2, 3, 4] res = reduce(lambda x, y: x*y, li) # 1 * 2 = 2 # 2 * 3 = 6 # 6 * 4 = 24 print(res) # Example 1: [1, 3, 5, 7, 9] --> 13579 def func(x, y): return x*10 + y print(reduce(func, [1, 3, 5, 7, 9])) # Example 2: The parameter passed in is'13579'---> 13579 # str -----> int digits = {'0':0, '1':1,'3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9} def StrToInt(s): def fn(x, y) return 10*x + y def CharToNum(s): return digits[s] return reduce(fn, map(CharToNum, s)) print(StrToInt('13579'))

3. filter() function
filter(func, iterable) filters Iterable based on the func, passing the data from the Iterable into the func, and if the function returns True, the data is retained, otherwise it is not retained

li = [1, 2, 3, 4, 5, 6, 7] Filter out all odd numbers print(list(filter(lambda x: x%2 == 1, li)))

4. sorted() function
sorted(iterable, key = None, reverse = False) sorts the data and returns a new object with the original unchanged.A key can be used to specify a sorting rule, and it accepts a value that is a function.Reverse is the order in which the sort is specified (ascending or descending), and the default is ascending.

List Derivation li = [] for i in range(10): li.append(i) print(li) # Quickly generate a list print([i for i in range(10)]) # Introducing a random number module from random import randint # Generate random numbers between -10 and 10 li = [randint(-10, 10) for _ in range(5)] print(li) # sort res1 = sorted(li) print(res1) # Add key: sort by absolute value res2 = sorted(li, key=abs) print(res2) # Sort in descending order res3 = sorted(li, key=abs, reverse=True) print(res3)

recursion

What is recursion:
1. Recursion is not an algorithm, but it is very useful
2. Recursive Definition: Calling the function itself within a function
3. Recursion is a technology that exists in many algorithms: backtracking, dynamic planning, dividing and conquering, etc.
Next, take the Fibonacci number as an example to use recursion to implement it:
Fibonacci sequence, also known as Golden Section Sequence and Rabbit Sequence.Fibonacci numbers are listed as 1, 1, 2, 3, 5, 8, 13, 21, 34...Starting with item 3, each item equals the sum of the first two items. The recursive formula is F(n)=F(n-1)+F(n-2), n=3, F(1)=1, F(2)=1.

# Using recursion to write Fibonacci series def fibo(k): # k stands for position number assert k > 0, 'k Value must be greater than 0' if k in [1, 2]: return 1 return fibo(k-1) + fibo(k-2) print(fibo(9))

Then, we'll use loops to implement the Fibonacci sequence to get a deeper understanding:

Using loops to implement Fibonacci series def fibo(k): assert k > 0, 'k Must be greater than 0' if k in [1, 2]: return 1 before1, before2 = 1, 1 # The purpose of the loop is to keep updating before1, before2 for _ in range(3, k+1): temp = before1 res = before1 + before2 before1 = res before2 = temp return res print(fibo(9))

Practice

Use recursion to implement the binary search algorithm.
Binary Search, also known as Binary Search, is an efficient search method.However, a half-fold lookup requires that linear tables must have a sequential storage structure and that the elements in the table are ordered by keywords.
Algorithmic idea: First, assume that the elements in the table are sorted in ascending order, and compare the keywords recorded in the middle position of the table with the search keywords. If the two are equal, the search will succeed; otherwise, the table will be divided into two sub-tables by using the middle position records. If the keywords recorded in the middle position are larger than the search keywords, the previous sub-table will be searched further; otherwise, after further search, the previous sub-table will be searched.A sub-table.Repeat the above process until you find a record that meets the criteria, make the search successful, or until the subtable does not exist, and the search is unsuccessful.

# Binary Search # Generate data from random import randint, choice data = [randint(1, 100) for _ in range(10)] # Randomly select one target = choice(data) data = sorted(data) print('The ordered array is', data) print('The target value to find is', target) # Using recursion to implement binary lookup def BinarySearch(left, right, data_list, target): """ left: Leftmost sequence number right: The rightmost sequence number data_list: List to find target: The number to look for """ # Find the middle ordinal value mid = int((left + right)/2) if data_list[mid] == target: return mid # The middle number is smaller than the target value, look right elif data_list[mid] < target: return BinarySearch(mid+1, right, data_list, target) # The middle number is larger than the target value, look left else: return BinarySearch(left, mid-1, data_list, target) res = BinarySearch(0, len(data)-1, data, target) print(res)
ZD_012 Twenty-five original articles have been published. Approved 0. Visits 702 Private letter follow

4 February 2020, 22:30 | Views: 4002

Add new comment

For adding a comment, please log in
or create account

0 comments