2020.2.5

递归

例一:(斐波那契数列)兔子生崽:有一对小兔子,第一个月处于生长状况,不具有繁殖能力其他每个月能生一对兔子,求一年之后兔子的总数:

数学函数:

当n = 1 或 n = 2时:F(n) = 1

当n >2时:F(n) = F(n-1)+F(n-2)

非递归:
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
	return n3
	
result = fab(12)
if result !=-1:
	print("共有%d对",result)
	
递归:
def fab(n):
	if n < 1:
		print("输入有误")
		return -1
	if n == 1 or n == 2:
		return 1
	else:
		return fab(n-1)+fab(n-2)

result = fab(12)
if result !=-1:
	print("共有%d对",result)

例二:汉诺塔

步骤:

1、将前n-1个盘子通过z从x移动到y上

2、将第n个盘子从x移动至z上

3、将前n-1个盘子通过x从y移动到z上

def hanoi(n,x,y,z):
	if n == 1:
		print(x,"-->",z)
	else:
		hanoi(n-1,x,z,y)
		print(x,'-->',z)
		hanoi(n-1,y,x,z)

n = int(input('请输入一个整数:'))
hanoi(n,'x','y','z')

字典:映射(大括号为其特点)

brand = ['李宁','耐克','阿迪达斯']
slogan = ['一切皆有可能','Just do it','Impossible is nothing']
ptint('阿迪达斯的口号是:',slogan[brand.index('阿迪达斯')])
输出:
阿迪达斯的口号是:Impossible is nothing
dict1 = {'李宁':'一切皆有可能','耐克':'Just do it','阿迪达斯':'Impossible is nothing'}
ptint('阿迪达斯的口号是:',dict1['阿迪达斯'])
输出:
阿迪达斯的口号是:Impossible is nothing

dict():创建一个字典

dict1 = dict((('F',70),('i',105),('s',115),('h',104)))
dict1
输出:
{'F':70,'i':105,'s':115,'h':104}

或者
dict1 = dict(F=70,i=105,s=115,h=104)
dict1
输出:
{'F':70,'i':105,'s':115,'h':104}

更改字典的值

dict1 = dict(F=70,i=105,s=115,h=104)
dict1['F'] = 88
dict1
输出:
{'F':88,'i':105,'s':115,'h':104}

字典的相关函数

fromkeys(S[,v]):创建并返回一个新的字典。S为字典的键值,可选参数v是S对应的值,且默认值为None(并不能更改字典的值)

dict1 = {}
dict1.fromkeys((1,2,3))
输出:
{1:None,2:None,3:None}
dict1,fromkeys((1,2,3),('one','two','three'))
输出:
{1:('one','two','three'),2:('one','two','three'),3:('one','two','three')}

访问字典的几种方法:

keys():返回字典键的引用

values():返回字典值的引用

items():

dict1 = {}
dict1.fromkeys(range(10),'h')
for eachKey in dict1.keys():
	print(eachKey)
输出:
0
1
2
3
4
5
6
7
8
9
for eachValue in dict1.valus():
	print(eachValue)
输出:
h
h
h
h
h
h
h
h
h
h
for eachItem in dict1.items():
	print(eachItem)
输出:
(0,'h')
(1,'h')
(2,'h')
(3,'h')
(4,'h')
(5,'h')
(6,'h')
(7,'h')
(8,'h')
(9,'h')

clear():清空字典里所有项目

copy():浅拷贝:复制了这个字典,并且存放于相同的地址

pop(s):返回要删除的值

popitem():返回要删除的键值对

setdefault(s[,v]):返回要加入字典的值,默认v为None

update():利用一个字典或映射关系去更新另一个字典

b = {'小白':'狗'}
a = {1:'one',2:'two','小白':'three'}
a.update(b)
a
输出:
{1:'one',2:'two','小白':'狗'}

集合(set):未体现映射关系的字典

set(元组,列表,字符串):使得括号内的类型转变为集合

set1 = set([1,2,3,4,5,4,3,2,1])
set1
输出:
{1,2,3,4,5}

例一:去除数组[1,2,3,4,5,5,3,1,0]中重复的元素

num1 = [1,2,3,4,5,5,3,1,0]
temp = []
for each in num1:
	if each not in temp:
		temp.append(each)
temp
输出:
[1,2,3,4,5,0]

或者

num1 = list(set(num1))
num1
输出:
[0,1,2,3,4,5]

add():添加一个不重复元素

remove():删除一个元素

不可变集合(frozen):稳定的不可添加的集合

frozenset():定义生成一个不可变集合

num3 = frozenset([1,2,3,4,5,0])
num3
输出:
[0,1,2,3,4,5]