递归:
python默认递归深入100层,设置递归深度:
import sys
sys.setrecursionlimit(层数)
函数自身调用自身
有一个明确的结束条件
def fun(n):
if n == 1:
return 1
else:
return n * fun(n-1)
pass
print(fun(5))
斐波那契非递归:
def fab(n):
n1 = 1
n2 = 1
n3 = 1
if n < 1:
print("输入有误!")
return -1
while (n-2) > 0:
n3 = n2 + n1
n1 = n2
n2 = n3
n -= 1
pass
return n3
result = fab(12)
if result != -1:
print('总共有%d对小兔子诞生!'%result)
递归斐波那契:
def Tu(n):
if n == 1 or n == 2:
return 1
else:
return Tu(n-1) + Tu(n-2)
pass
print(Tu(12))
字典:
字典默认值:None
字典名 = {key:value,key:value}
dict(key=value,key=value) dict字典类型工厂函数,key为字符串时,不可加引号
调用:
字典名[key]
keys() 拿到字典的key
values() 拿到字典的value
items() 拿到字典key和value
clear() 清空字典
copy() 拷贝
id(变量) 查看内存地址
pop(key) 弹出键值对
popitem() 按优先级弹出键值对
setdefault(key,value) 当字典里不存在该key时,会自动添加
集合:
{数值,数值}
唯一
set(列表)
add() 集合追加数值
不可变集合 frozenset([列表])
open(路径\文件名,打开方式) 打开文件
打开方式:
'r' 以只读方式打开(默认)
'w' 以写入的方式打开文件,会覆盖已存在文件
'x' 如果文件已存在,使用此模式打开将引发异常
'a' 以写入模式打开,如果文件存在,则在末尾追加写入
'b' 以二进制模式打开
't' 以文本形式打开(默认)
'+' 可读写模式(可添加到其他模式中使用)
'U' 通用换行符支持
文件对象方法:
close() 关闭文件
read(size=-1) 从文件读取size个字符,当未给定size或给负值时,读取剩余的所有字符,然后作为字符串返回
readline() 以写入模式打开,如果文件存在,则在末尾追加写入
write(str) 将字符串写入文件
writelines(seq) 向文件写入字符串序列seq,seq应该是一个返回字符串的可
迭代对象
seek(offset,from) 在文件中移动文件指针,从from(0代表文件起始位置,1代表当前位置,2代表文件末尾)偏移offset个字节
tell() 返回当前在文件中的位置
文本分割:
file = open('duihua.txt')
boy = []
girl = []
count = 1
for each_line in file:
#判断前6个字符是否为=号
if each_line[:6] != '======':
#字符串分割:
(role,line_spoken) = each_line.split(':',1)
if role == '天道':
boy.append(line_spoken)
pass
if role == '鸣人':
girl.append(line_spoken)
else:
#文件分别保存
file_name_boy = 'boy_' + str(count) + '.txt'
file_name_girl = 'girl' + str(count) + '.txt'
boy_file = open(file_name_boy,'w')
girl_file = open(file_name_girl,'w')
boy_file.writelines(boy)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
boy = []
girl = []
count += 1
pass
pass
file_name_boy = 'boy_' + str(count) + '.txt'
file_name_girl = 'girl' + str(count) + '.txt'
boy_file = open(file_name_boy,'w')
girl_file = open(file_name_girl,'w')
boy_file.writelines(boy)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
file.close()
文本分割:
def save_file(boy,girl,count):
boy_name_file = 'boy' + str(count) + '.txt'
girl_name_file = 'girl' + str(count) + '.txt'
boy_file = open(boy_name_file,'w')
girl_file = open(girl_name_file,'w')
boy_file.writelines(boy)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
pass
def fb_file(file_name):
f = open(file_name)
boy = []
girl = []
count = 1
for each_line in f:
if each_line[:6] != '======':
(role,line_spoken) = each_line.split(':',1)
if role == '天道':
boy.append(line_spoken)
if role == '鸣人':
girl.append(line_spoken)
else:
save_file(boy,girl,count)
boy = []
girl = []
count += 1
pass
pass
save_file(boy,girl,count)
pass
fb_file('duihua.txt')
转载于:https://blog.51cto.com/3945465/2346654