Day5 函数高级和模块

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Day5 函数高级和模块相关的知识,希望对你有一定的参考价值。

一 函数高级

1.1 递归函数

在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数。

def calc(n):
    print(n)

    if int(n/2) ==0:

        return n

    return calc(int(n/2))

calc(10)

#输出:

10

5

2

1

 递归特性:

  1.  必须有一个明确的结束条件
  2. 每次进入更深一层递归时,问题规模相比上次递归都应有所减少
  3. 递归效率不高,递归层次过多会导致栈溢出(在计算机中,函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用,栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出)

堆栈扫盲http://www.cnblogs.com/lln7777/archive/2012/03/14/2396164.html 

1.1.2 二分查找

data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35]

def binary_search(dataset,find_num):
    print(dataset)

    if len(dataset) >1:

        mid = int(len(dataset)/2)

        if dataset[mid] == find_num: #find it

            print("找到数字",dataset[mid])

        elif dataset[mid] > find_num :# 找的数在mid左面

            print("\\033[31;1m找的数在mid[%s]左面\\033[0m" % dataset[mid])

            return binary_search(dataset[0:mid], find_num)

        else:# 找的数在mid右面

            print("\\033[32;1m找的数在mid[%s]右面\\033[0m" % dataset[mid])

            return binary_search(dataset[mid+1:],find_num)

    else:

        if dataset[0] == find_num: #find it

            print("找到数字啦",dataset[0])

        else:

            print("没的分了,要找的数字[%s]不在列表里" % find_num)

binary_search(data,66)

1.1.3 python中的递归效率低且没有尾递归优化

#python中的递归
python中的递归效率低,需要在进入下一次递归时保留当前的状态,在其他语言中可以有解决方法:尾递归优化,即在函数的最后一步(而非最后一行)调用自己,尾递归优化:http://egon09.blog.51cto.com/9161406/1842475
但是python又没有尾递归,且对递归层级做了限制

#总结递归的使用:
1. 必须有一个明确的结束条件

2. 每次进入更深一层递归时,问题规模相比上次递归都应有所减少

3. 递归效率不高,递归层次过多会导致栈溢出(在计算机中,函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用,栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出)

1.1.4 可以修改递归最大深度

import sys
sys.getrecursionlimit()
sys.setrecursionlimit(2000)
n=1
def test():
    global n
    print(n)
    n+=1
    test()

test()

虽然可以设置,但是因为不是尾递归,仍然要保存栈,内存大小一定,不可能无限递归

 

1.2 匿名函数(lambda表达式)

匿名函数就是不需要显式的指定函数

#这段代码

def calc(n):
    return n**n

    print(calc(10))

#换成匿名函数

calc = lambda n:n**n
print(calc(10))

你也许会说,用上这个东西没感觉有毛方便呀, 。。。。呵呵,如果是这么用,确实没毛线改进,不过匿名函数主要是和其它函数搭配使用的呢,如下:

res = map(lambda x:x**2,[1,5,7,4,8])

for i in res:

    print(i)

输出

1
25
49
16
64

 

1.3 内置函数

abs #绝对值
all #判断列表里所有值都为真,返回ture,否则返回false

any #判断列表里有任一个值为真,返回ture,否则返回false

ascii #

bin #将一个数字转换为二进制

bool #判断真假

bytearray#允许修改字符串
b = babc
c = bytearray(b)
c[0] #97
c[0] = 90
c #bytearray(b‘Zbc)

bytes #将输入的内容转换为bytes

callable #判断一个对象是否可调用(调用不是引用,是可执行的意思)

chr #给一个Asicc值,判断结果print chr(68)?D

ord #字符转数字 print(ord(‘d‘)

classmethod#

compile#

complex#输入一个值,返回复数 ==complex(4,5)

exec #执行exec括号里的代码

eval #执行括号里的运算

delattr#

dict #生成字典

dir #查看内置方法

divmod #两个参数相除,返回商和余数divmod(4,3)

enumerate#生成序列

filter#True序列 print(filter(lambda x:x==1,[1,23,4]))

map#遍历列表中的值print(map(lambda x:x+1,[1,2,3]))

reduce#累加print(reduce(lambda x,y:x+y,[1,2,3]))

float#转成浮点

format#字符串格式化

frozenset#冻结集合,frozenset({1,2,4,5,5})之后,只读集合

getattr#

globals#把当前程序在内存中的空间全部打印print(globals())

locals #打印局部的

hash #转为hash

hex #转为16进制

id #查看内存地址

input #输入

int #转为整数

isinstance #判断是不是一个实例

issubclass #判断是不是一个子类

iter #

len #判断长度

list #生成列表

max #输出最大值

memoryview #

min #输出最小值

next #

object #

oct #转为八进制

open #打开文件

pow#幂运算 print(pow(4,9))

print #打印

property#

range #随机数

repr #

reversed #反转,可反转字符串

round #四舍五入 print(round(10.23,1))

set #生成集合

setattr #
slice #
a = range(20)
pattern = slice(3,8,2)
for i in a[pattern]: #等于a[3:8:2]
print(i)

sorted #排序,可排序字符串

staticmethod #

str #生成字符串

sum #求和

super #

tuple #生成元组

type #判断数据类型

vars #同 globals

zip #传n个列表,生成n个序列
>>> x = [1,2,3]
>>> y = [4,5,6]
>>> z = [7,8,9]
>>> print zip(x,y,z)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

 

以上是关于Day5 函数高级和模块的主要内容,如果未能解决你的问题,请参考以下文章

day5模块

Python Day5

day5

python day5

Day5 - 常用模块学习

Python 之路 Day5 - 常用模块学习