Recursion and built-in functions

Recursion

What is a recursive function

Nested function calls: function nested functions. Recursive function calls: it is a special kind of nested call, but it calls a function of the process, and directly or indirectly calls itself.

def foo():
    print('from foo')
    foo()

# foo()  #进入死循环

If ever a recursive function calls the function itself, then this recursive function will enter an infinite loop, so we should give a clear recursive function termination condition.

Direct call

Direct call means: direct call function within the function itself.

import sys

print(f'最大递归层数:{sys.getrecursionlimit()}')
最大递归层数:3000
import sys

# 修改递归层数
sys.setrecursionlimit(10000)


def foo(n):
    print('from foo', n)
    foo(n+1)
# foo(0)

Indirect call

Indirect call means: do not call the original function in vivo function itself, but to call the function itself through other indirect methods.

def bar():
    print('from bar')
    foo()


def foo():
    print('from foo')
    bar()

# bar()

Recursive must have two distinct phases:

  1. Recursive: recursive call down layer by layer, into the next level of recursion scale of the problem will be reduced.
  2. Back: there must be a clear recursive end condition, the condition is satisfied in the back layer by layer to start.

The essence is that by repeating recursive approach a final result constantly.

'''
...
age(5) = age(4) + 2
age(4) = age(3) + 2
age(3) = age(2) + 2
age(2) = age(1) + 2
age(1) = 26


age(n) = age(n-1) + 2
age(1) = 26    # n =1
'''


def age(n):
    if n == 1:
        return 26
    res = age(n - 1) + 2
    return res


print(f'age(6):{age(6)}')
age(6):36

Why use recursion

Recursive nature is doing repeat jobs, but only ordinary repeat, we use a while loop it.

lis = [1, [2, [3, [4, [5, [6, ]]]]]]


def tell(lis):
    for i in lis:
        if type(i) is list:
            tell(i)
        else:
            print(i)


tell(lis)
1
2
3
4
5
6

How recursion

Dichotomy applications

nums = [1, 3, 5, 6, 7, 8, 2, 8, 9, 0, 23, 5, 43]

for i in nums:
    if i == 10:
        print('find it')
        break
else:
    print('not exist')
not exist

When the list came from data comparison, for the demand loop can be achieved, but the elements very long, it is very complicated, so we consider the idea of ​​dichotomy implementation.

from random import randint
nums = [randint(1, 100) for i in range(100)]
nums.sort()
print(nums)
[1, 4, 4, 5, 6, 6, 6, 6, 8, 9, 9, 9, 11, 11, 15, 15, 16, 16, 17, 18, 18, 18, 19, 20, 24, 27, 28, 32, 33, 33, 35, 36, 37, 38, 38, 39, 41, 42, 46, 46, 46, 47, 48, 49, 49, 50, 50, 52, 53, 54, 54, 56, 56, 59, 60, 61, 61, 61, 62, 63, 63, 64, 65, 67, 68, 68, 69, 70, 70, 70, 70, 71, 72, 72, 74, 75, 75, 77, 77, 77, 78, 79, 80, 82, 82, 83, 83, 84, 85, 86, 86, 86, 86, 89, 89, 91, 96, 97, 99, 99]
def search(search_num, nums):
    mid_index = len(nums)//2
    print(nums)
    if len(nums) == 1 and nums[0] != search_num:
        print('not exist')
        return
    if search_num > nums[mid_index]:
        nums = nums[mid_index:]
        search(search_num, nums)
    elif search_num < nums[mid_index]:
        nums = nums[:mid_index]
        search(search_num, nums)
    else:
        print('find it')


search(7, nums)
[1, 4, 4, 5, 6, 6, 6, 6, 8, 9, 9, 9, 11, 11, 15, 15, 16, 16, 17, 18, 18, 18, 19, 20, 24, 27, 28, 32, 33, 33, 35, 36, 37, 38, 38, 39, 41, 42, 46, 46, 46, 47, 48, 49, 49, 50, 50, 52, 53, 54, 54, 56, 56, 59, 60, 61, 61, 61, 62, 63, 63, 64, 65, 67, 68, 68, 69, 70, 70, 70, 70, 71, 72, 72, 74, 75, 75, 77, 77, 77, 78, 79, 80, 82, 82, 83, 83, 84, 85, 86, 86, 86, 86, 89, 89, 91, 96, 97, 99, 99]
[1, 4, 4, 5, 6, 6, 6, 6, 8, 9, 9, 9, 11, 11, 15, 15, 16, 16, 17, 18, 18, 18, 19, 20, 24, 27, 28, 32, 33, 33, 35, 36, 37, 38, 38, 39, 41, 42, 46, 46, 46, 47, 48, 49, 49, 50, 50, 52, 53, 54]
[1, 4, 4, 5, 6, 6, 6, 6, 8, 9, 9, 9, 11, 11, 15, 15, 16, 16, 17, 18, 18, 18, 19, 20, 24]
[1, 4, 4, 5, 6, 6, 6, 6, 8, 9, 9, 9]
[6, 6, 8, 9, 9, 9]
[6, 6, 8]
[6, 8]
[6]
not exist

Anonymous function

A named function

Before given function are well-known function, which is based on the use of the function name.

def func():
    print('from func')


func()
from func

Anonymous function

Anonymous function, it does not bind the name, ie, once recovered, brackets to run.

lambda x,y :x+y
<function __main__.<lambda>(x, y)>
res = (lambda x,y :x+y)(3,5)
print(res)
8

Built-in function in combination with

Generally anonymous functions max (), sort (), filter (), sorted () method in combination.

salary_dict = {
    'willaim':15000
    'tom':12000
    'jerry':10000
}

1. If we want to remove the highest-paid people from the dictionary, we can use the max () method, but the max () the comparison is the default dictionary key.

  1. First iterables become iterator object
  2. res = next (iterator object), the parameters passed to the function key res as specified, then the return value of the function as a judgment basis.
salary_dict = {
    'willaim':15000,
    'tom':12000,
    'jerry':10000,
    'zalexsandra':14000
}

print(f'max(salary-dict):{max(salary_dict)}')

def func(k):
    return salary_dict[k]

print(f'max(salary_dict,key=func):{max(salary_dict,key=func)}')

print(f'max(salary_dict,key=lambda name:salary_dict[name]):{max(salary_dict,key=lambda name:salary_dict[name])}')
max(salary-dict):zalexsandra
max(salary_dict,key=func):willaim
max(salary_dict,key=lambda name:salary_dict[name]):willaim

2. To the above dictionary person descending order according to pay, may be used sorted () method.

sorted () works:

  1. First iterables become iterator object
  2. res = next (iterator object), res as the argument to the second argument specifies the function, and returns the value of the function as a judgment basis.
lis = [1,4,2,7,45,9,3]
lis = sorted(lis)
print(f'lis:{lis}')
print(f'sorted(lis,reverse=True):{sorted(lis,reverse=True)}')
lis:[1, 2, 3, 4, 7, 9, 45]
sorted(lis,reverse=True):[45, 9, 7, 4, 3, 2, 1]
salary_dict = {
    'willaim':15000,
    'tom':12000,
    'jerry':10000,
    'zalexsandra':14000
}

print(f'sorted(salary_dict,key=lambda name:salary_dict[name]):{sorted(salary_dict,key=lambda name:salary_dict[name])}')
sorted(salary_dict,key=lambda name:salary_dict[name]):['jerry', 'tom', 'zalexsandra', 'willaim']

3. If we want a list of names to do a deal, you can use the map () method.

map () works:

  1. First iterables become iterator object
  2. res = next (iterator object), the parameters passed to the function res as specified by the first parameter, and then returns as one map () method of the function result value.
name_list = ['tom','jerry','sandra']

res = map(lambda name:f'{name} is funny',name_list)
print(list(res))
['tom is funny', 'jerry is funny', 'sandra is funny']

4. If we want to filter contains the name of the name 'funny' in addition, we can use the filter () method.

filter () works:

  1. First iterables become iterator object
  2. res = next (iterator object), the parameters passed to the function res as specified by the first parameter, and then returns the filter function determines the value true or false, if true left.

Built-in functions

grasp

1.bytes()

2.chr () / word ()

3.divmod()

4.enumerate()

5.eval()

6.hash()

# bytes() 解码字符

res = '你好'.encode('utf8')
print(res)

res = bytes('你好',encoding='utf8')
print(res)
b'\xe4\xbd\xa0\xe5\xa5\xbd'
b'\xe4\xbd\xa0\xe5\xa5\xbd'
# chr()参考ASCII码表将数字转换为对应字符;ord()将字符转换为对应数字。
print(chr(65))

print(ord('B'))
A
66
# divmod() 分栏  (x//y,x%y)

print(divmod(10,3))
(3, 1)
# enumerate() 带有索引迭代

lis = ['a','b','c','d']
for i in enumerate(lis):
    print(i)
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
# eval() 把字符串翻译成数据内型,''里面必须是数据类型

s = '[1,2,3]'
lis_eval = eval(s)
print(type(s))
print(lis_eval,type(lis_eval))
<class 'str'>
[1, 2, 3] <class 'list'>
# hash() 是否可哈希,可哈希则不可变

print(hash(1))

# print(hash([1,2,3]))  TypeError: unhashable type: 'list'
1

To understanding

1.abs()

2.all()

3.any()

4.bin()/oct()/hex()

5.dir ()

6.frozenset()

7.globals () / local ()

8.pow()

9.round()

10.slice()

11.sum()

12.import()

# abs() 求绝对值

print(abs(-18))
18
# all() 可迭代元素全为真,则返回真。

print(all([0,1,2,3,4]))

print(all([]))
False
True
# any() 可迭代对象中有一元素为真,则为真
print(any([1,0,None]))

print(any([]))
True
False
# bin()/oct()/hex() 二进制、八进制、十六进制

print(bin(17))

print(oct(17))

print(hex(17))
0b10001
0o21
0x11
# dir() 列举模块所有功能

import time

print(dir(time))
['_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'altzone', 'asctime', 'clock', 'ctime', 'daylight', 'get_clock_info', 'gmtime', 'localtime', 'mktime', 'monotonic', 'perf_counter', 'process_time', 'sleep', 'strftime', 'strptime', 'struct_time', 'time', 'timezone', 'tzname']
# frozenset() 集合变为不可更改

s = {1,2,3}
s.add(4)
print(s)
s = frozenset(s)
# s.add(5)  AttributeError: 'frozenset' object has no attribute 'add'
print(s)
{1, 2, 3, 4}
frozenset({1, 2, 3, 4})
# globals()/locals() 查看全局名字;查看局部名字

#print(globals())

#print(locals())
# pow() 

print(pow(3,2,2))   # (3**2)%2
1
# round()  四舍五入

print(round(3.5))

print(round(3.4))
4
3
# slice() 

lis = ['a','b','c']
s = slice(1,4,1)
print(lis[s]) # print(lis[1:4:1])
['b', 'c']
# sum()

print(sum(range(1,101)))
5050
# __import__() 通过字符串导入模块

m = __import__('time')
print(m.time())
1559718343.887399

Guess you like

Origin www.cnblogs.com/WilliamKong94/p/11005382.html