#汉诺塔
steps = []
def move(n, a="A", b="B", c="C"):
if n == 1:
step = a + "-->" + c #1个时,直接从A移到C
steps.append(step)
else:
move(n-1, a,c,b) #将n-1个借助C从A移到B 再把最大的从A移到C
step = a + "-->" + c
steps.append(step)
move(n-1, b, a, c) #将n-1个借助A从B移到C
move(3)
print("移动次数为:%d \n操作步骤为:\n%s" % (len(steps),steps))
方法1
def fibonacci(n):
a = 1
L = [1,1]
while a < n:
x = L[-1] + L[-2]
L.append(x)
a = a + 1
return L
print(fibonacci(20))
方法2
def fib(max):
n, a, b = 0, 0, 1
while n < max:
print(b)
a, b = b, a + b
n = n + 1
使用生成器实现
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return 'done'
g = fib(6)
while True:
try:
x = next(g)
print('g:', x)
except StopIteration as e:
print('Generator return value:', e.value)
break
使用生成器实现
def triangles():
ret = [1]
while True:
yield ret
for i in range(1, len(ret)):
ret[i] = pre[i] + pre[i - 1]
ret.append(1)
pre = ret[:]
n = 0
for x in triangles():
print(x)
n = n + 1
if n == 10:
break
使用列表生成式和生成器
def triangles(n):
L = [1]
m = 0
while m < n:
yield L
L.append(0)
L = [L[i - 1] + L[i] for i in range(len(L))]
m = m + 1
l = triangles(10)
for x in l:
print(x)
#定义一个从3开始的奇数序列
def _odd_iter():
n = 1
while True:
n = n + 2
yield n
#定义一个筛选函数 过滤点可以被之前的数整除的数字
def _not_divisible(n):
return lambda x: x % n > 0
#定义一个生成器,不断返回下一个素数
def primes():
yield 2
it = _odd_iter() # 初始序列
while True:
n = next(it) # 返回序列的第一个数
yield n
it = filter(_not_divisible(n), it) # 构造新序列
# 打印1000以内的素数:
for n in primes():
if n < 1000:
print(n)
else:
break
def is_palindrome(n):
return str(n) == str(n)[::-1]
output = filter(is_palindrome, range(1, 1000))
print(list(output))