1、冒泡排序
1 def foo(list): 2 n = len(list) 3 for i in range(n): 4 for j in range(0, n-i-1): 5 if list[j] > list[j+1]: 6 list[j], list[j+1] = list[j+1], list[j] 7 return list
2、二分查找
1 def foo1(list, item): 2 low = 0 3 high = len(list) - 1 4 while low <= high: 5 mid = (high - low) // 2 + low 6 guess = list[mid] # 中位数 7 if guess > item: 8 high = mid -1 9 elif guess < item: 10 low = mid + 1 11 else: 12 return mid
3、水仙花数(1000内取值)
1 def foo2(num): 2 a = num // 100 # 百位取余 3 b = num % 100 // 10 # 10位取余 4 c = num % 10 # 个位取余 5 d = a ** 3 + b ** 3 + c ** 3 6 if num == d: 7 print(num)
4、斐波那契数列
1 def foo(num): 2 if num <= 1: 3 return num 4 else: 5 return foo(num-1) + foo(num-2)
1 def foo(num): 2 n, a, b = 0, 0, 1 3 while n < num: 4 print(b) 5 a, b = b, a+b 6 n = n + 1