问题1
实现斐波那契数列1,1,2,3,5,8,13,21,…
def fibonacci1(n):
assert(n>=0)
if (n <= 2):
return 1
return fibonacci1(n-1) + fibonacci1(n-2)
fibonacci1(8)
result---------------------------------------
21
#这种写法展开就是一棵二叉树(当前值由前两个值决定),因此时间复杂度是o(2^n),十分不推荐
def fibonacci2(n):
a = 0
b = 1
for i in range(1, n+1):
a, b = b, a+b
return a
fibonacci2(8)
result---------------------------------------
21
#这是最好的写法
def fibonacci3(n):
if n<=1:
return (0,1)
(a, b) = fibonacci3(n-1)
return (b, a+b)
fibonacci3(8)
result---------------------------------------
(13, 21)
#这是递归的另一种写法,复杂度为n,可以接受
问题2
已知a,b且a ⩽ \leqslant ⩽b, 要求用a表示b。只能用+1和*2
def intSeq(a, b):
if (a == b):
return str(a)
if (b % a == 1):
return "(" + intSeq(a, b-1) + " + 1)"
if (b < a * 2):
return "(" + intSeq(a, b-1) + " + 1)"
return intSeq(a, b/2) + " * 2";
a = 5;
b = 101;
print(str(b) + " = " + intSeq(a, b))
reslut---------------------------------
101 = (((5 + 1) * 2 * 2 + 1) * 2 * 2 + 1)