本学习系列介绍:
本学习系列主要针对对编程略有了解或有其他语言基础并要进一步学习Python的同学,通过简易的代码快速入门掌握Python语言。
系列总目录: |
---|
用简易代码快速学习Python(一) |
用简易代码快速学习Python(二) |
用简易代码快速学习Python(三) |
用简易代码快速学习Python(四) |
用简易代码快速学习Python(五) |
用简易代码快速学习Python(六) |
用简易代码快速学习Python(七) |
用简易代码快速学习Python(八) |
用简易代码快速学习Python(九) |
用简易代码快速学习Python(十) |
今天内容较少,但请深入理解。
Day04:
递归:
汉诺塔问题:
count= 0
def hanoi(n, x, y, z):
global count
if n==1:
count += 1
print('第', count, '步:将', n, '号木块从', x, '移动到', z, '上')
else:
hanoi(n-1, x, z, y)
count += 1
print('第', count, '步:将', n, '号木块从', x, '移动到', z, '上')
hanoi(n-1, y, x, z)
n = int(input("请输入汉诺塔层数:"))
hanoi(n, 'A', 'B', 'C')
print('结论:%d层的汉诺塔移动一共需要用 %d 步' % (n, count))
字典:
注意:字典是没有顺序的、可改变的。
字典的标识为{}。
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object’s (key, value) pairs
dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)
例如:
dict1 = {'F': 70, 'i': 105, 's': 115, 'h': 104, 'C': 67}
print(dict1) #输出:{'F': 70, 'i': 105, 's': 115, 'h': 104, 'C': 67}
dict1 = dict((('F',70),('i',105),('s',115),('h',104),('C',67)))
print(dict1) #输出:{'F': 70, 'i': 105, 's': 115, 'h': 104, 'C': 67}
dict1 = dict(a='aaa',b='bbb') #注意:此时字符串作为key时不用引号。
print(dict1) #输出:{'a': 'aaa', 'b': 'bbb'}
dict1['c'] = 'ccc' #若索引在字典中未出现,可以直接添加到字典中。
print(dict1) #输出:{'a': 'aaa', 'b': 'bbb', 'c': 'ccc'}
dict1 = {'a':'haha'}
dict1 = dict1.fromkeys(range(5), '赞')
print(dict1) #输出:{0: '赞', 1: '赞', 2: '赞', 3: '赞', 4: '赞'}
print(dict1[6]) #报错,因为key不存在。
print(dict1.get(3)) #输出:赞
print(dict1.get(6)) #输出:None
print(dict1.get(3, 'good')) #输出:赞
print(dict1.get(6, 'good')) #输出:good
a = {'name':'lxy'}
b = a
print(b) #输出:{'name':'lxy'}
a = {}
print(b) #输出:{'name':'lxy'}
a = {'name':'lxy'}
b = a
print(b) #输出:{'name':'lxy'}
a.clear()
print(b) #输出:{}
a = {'name':'lxy'}
b = a.copy()
c = a
print(id(a)) #输出a的地址
print(id(b)) #输出b的地址,与a的地址不同。
print(id(c)) #输出c的地址,与a的地址相同。
a = {'name':'lxy', 'age':20}
b = {'age':23, 'id':123456}
a.update(b)
print(a) #输出:{'name': 'lxy', 'age': 23, 'id': 123456}