分享

Python算法.4

 云深无际 2021-11-03

Python算法.3

Python 算法.2

Python算法.1

colors=['black','white']sizes=['S','M','L']tshirts=[(color,size) for color in colors for size in sizes]# 推导式,先写要生成的东西。然后按照循环顺序写循环print(tshirts)

计算笛卡尔积

for color in colors: for size in sizes: print((color,size))

用传统的循环写展开式

tshirts =[ (color,size) for size in sizes for color in colors]print(tshirts)

colors=['black','white']sizes=['S','M','L']for tshirts in ('%s%s'%(c,s) for c in colors for s in sizes): # 变成了圆括号 print(tshirts)

生成器表达式计算笛卡尔积,注意是写成了元组

if __name__ == "__main__": i = 0 print("A,B,C三人所选书号分别为:") for a in range(1, 6): for b in range(1, 6): for c in range(1, 6): if a != b and a != c and c != b: print("A:%2d B:%2d C:%2d" % (a, b, c), end='') i += 1 if i % 4 == 0: print()print("共由%d种有效借阅方法" % i)

三人选书不可以重复选

# 汉诺塔def moveDisk(i,x,y): print("移动盘子",i,"从",x,"到",y) # 盘子数,起始柱子,中转柱子,目标柱子def move(n,a,b,c): if n>1: move(n-1,a,c,b) moveDisk(n,a,c) move(n-1,b,a,c)
move(5,"A","B","C")

汉诺塔问题

# 求阶乘def fact(n): if n==1: return 1 return n*fact(n-1)
fact(4)
def fib(n): if n<=2: return 1 else: return fib(n-1)+fib(n-2)
for i in range(8): print(fib(i),end=', ')

两个fib的写法

def binarySearch(alist, value): if len(alist) == 0: # 空序列 return -1 else: Middle=len(alist)//2 if alist[Middle]==value: # 中间元素对比 return Middle else: if value<alist[Middle]: # 左区间查找 return binarySearch(alist[:Middle],value) else: # 右区间查找 return binarySearch(alist[Middle+1:],value)
testlist=[5,6,7,8,9,12,34,46,67,86,98,1222]print(binarySearch(testlist,34))

二分法

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多