Python基础知识5-递归函数、生成器
函数执行流程*
递归Recursion
递归的性能
递归总结
递归练习:
#1 def fac(n): if n==1: return n return n*fac(n-1) def fac1(n, f=1): if n == 1: return f f *= n return fac1(n - 1, f)
#2 def revert1(n,lst=[]): lst.append(n%10)#可以考虑用divmod()函数 return lst if n//10==0 else revert1(n//10,lst) def revert1(num,tarhet=[]): if str(num): target.append(num[len(num)-1]) revert1(num[:len(num)-1]) return target
#3 ef peach1(days=10): if days==1: return 1 return (peach1(days-1)+1)*2 def peach2(days=1): if days==10: return 1 return (peach2(days+1)+1)*2
匿名函数
生成器***
生成器应用
yield from
练习:
#1.#利用isinstance判断是否是字典,是的继续递归,否则合并key,赋值新字典 source = {'a': {'b': 1, 'c': 2}, 'd': {'e': 3, 'f': {'g': 4}}} # # target = {'a.b': 1, 'd.f.g': 4, 'd.e': 3, 'a.c': 2} target={} def func(src,targetkey=''): if not isinstance(src,dict): return None for k,v in src.items(): if isinstance(v,dict): func(v,targetkey=targetkey+k+'.') else: target[targetkey+k]=v
#参考:https://www.cnblogs.com/bolenzhang/p/8366365.html alphabet=b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" #参照Base64编码表 def base64(src): ret = bytearray() length = len(src) # r记录补0的个数 r = 0 for offset in range(0, length,3): if offset + 3 <= length: triple = src[offset:offset+3] else: triple = src[offset:] r = 3 - len(triple) triple = triple + '\x00'*r print(triple.encode(),r) #int.from_bytes函数参考:https://blog.csdn.net/Clovera/article/details/79293108 b = int.from_bytes(triple.encode(), 'big')#bytes类型的变量x,转化为十进制整数 print(b)
#01100001 for i in range(18, -1, -6): if i == 18: index = b >> i else: index = b >>i & 0x3F #十六进制3f等于十进制63,二进制表示为 0011 1111,因为我们是按6位取 ret.append(alphabet[index]) for i in range(1,r+1): ret[-i] = 0x3D return ret print(base64('abcd'))
#ASCII码与字符相互转换
ord()函数:它以一个字符(长度为1的字符串)作为参数,返回对应的 ASCII 数值。
chr()函数:在 range(256)内的(就是0~255)整数作参数,返回当前整数对应的ASCII字符。
#3#动态规划方法! str1 = 'ahcdef' str2 = 'hcadef' def maxSubstring(str1,str2): if not str1 or not str2: return None length1 = len(str1) length2 = len(str2) #建立辅助二维数组 arr = [[0 for i in range(length1+1)]for j in range(length2+1)] p = 0#用于记录最大长度的下标 maxlength = 0#记录最大的子串长度 for i in range(length1): for j in range(length2): if str1[i] == str2[j]: arr[i+1][j+1] = arr[i][j] + 1 if arr[i+1][j+1]>maxlength: maxlength = arr[i+1][j+1] p = i+1 return str1[p-maxlength:p],maxlength
做一枚奔跑的老少年!