1.递归满足的两个条件:函数调用自身、设置了正确的返回条件;
2.适合使用递归的情况:目录索引、树结构、快速排序等;、
====斐波那契数列计算====
#递归法:
def fib(n): if n==0 or n==1: return 1 else: return fib(n-1)+fib(n-2)num = int(input("请输入一个数:"))print fib(num)#迭代法:
def fib1(n): if n==0 or n==1: return 1 else: a = 0 b = 1 for i in range(n): i = a a = b b = i + a return b >>> num=int(input("请输入一个数:")) 请输入一个数:10 >>> print fib1(num) 55 >>> fib1(5) 53.字典
索引不好用时怎么办?
>>> dict1={}>>> dict1.fromkeys((1,2,3)){1: None, 2: None, 3: None}>>> dict1.fromkeys((1,2,3),'number'){1: 'number', 2: 'number', 3: 'number'}
# 访问字典的方法:keys(),value(),items()
keys:返回字典键的引用;values():返回字典值的引用;items():返回所有项
>>> dict2={}>>> dict2=dict2.fromkeys(range(10),'赞')>>> for eachkey in dict2.keys(): print eachkey
#get方法:试图访问字典中不存在的项时打印出None
>>> print dict2.get(32)None>>> print dict2.get(32,'木有')木有>>> 32 in dict2False
#清空字典使用clear()方法
>>> dict2.clear()>>> dict2{}
#pop给定键弹出对应的值,popitem弹出指定的项
>>> a={1:'one',2:'two',3:'three'}>>> a.pop(2)'two'
>>> a.popitem()(1, 'one')
# update利用字典映射关系更新一个字典
>>> b={'小白':'狗'}>>> a={1:'one',2:'two',3:'three'}>>> a.update(b)>>> a{1: 'one', 2: 'two', 3: 'three', '\xd0\xa1\xb0\xd7': '\xb9\xb7'}
=====集合=====
4.集合
用花括号括起一堆没有映射关系的元素就为集合形式,集合中的数均为唯一性,会自动将重复的数清楚掉,集合没有顺序。
去掉重复元素:
方法一:利用for把其中数据一一读取,利用in和not in判断一个元素是否在集合中已经存在
>>> num1=[1,2,2,3,3,4,5]>>> temp=[]>>> for each in num1: if each not in temp: temp.append(each)
>>> temp[1, 2, 3, 4, 5]
方法二:利用集合,但集合得到的结果是无序的>>> num1 = list(set(num1))>>> num1[1, 2, 3, 4, 5]
#frozen冻结集合中的元素,不可改变
>>> num2=frozenset([1,2,3,4])
转载于:https://www.cnblogs.com/fancycheng/p/7631771.html
