1、台阶问题、斐波那契
一只青蛙可以跳上一级台阶,也可以跳上两级台阶,求青蛙跳上一个n级台阶共有多少种跳法
方法一:
def fib(n):
a, b = 0,1
for _ in range(n):
a, b = b, a+b
return b
方法二:
def fib(n):
a, b = 0,1
for _ in range(n):
a, b = b, a+b
return b
方法三:
def memo(func):
cache = {}
def wrap(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
return wrap
@memo
def fib(n):
if n < 2:
return 1
return fib(n-1) + fib(n-2)
2、台阶问题、斐波那契
一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。
求该青蛙跳上一个n级的台阶总共有多少种跳法。
fib = lambda n : n if n < 2 else 2*fib(n-1)
3、矩形覆盖问题
第2n个矩形的覆盖方法等于第2(n-1)加上第2(n-2)的方法。
area = lambda i :i if i < 2 else area(n-1) + area(n-2)
4、杨氏矩阵查找
在一个m行n列二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
data = [[1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]]
def find_young(data,target):
m = len(data) - 1
n = len(data[0]) - 1
r = 0
c = n
while c>=0 and r<=m: #从左上方开始查询
value = data[r][c]
if value == target:
return True
elif value > target:
c -= 1
elif value < target:
r += 1
return False
5、去除列表中的重复元素
list1 = ['b','c','d','b','c','a','a']
-
用集合
list(set(data))
-
用字典
l2 = {}.fromkeys(list1).keys() #说明:用于创建一个新字典,以序列seq中元素做字典的键
-
用字典并保持顺序
l2 = list(set(list1)) l2.sort(key=l1.index)
-
列表推导式
l2 = [] [l2.append(i) for i in list1 if not i in l2]
6、链表成对
1->2->3->4转换成2->1->4->3
obj = Solution()
for i in range(10):
obj.append(i)
class ListNode:
def __init__(self, x):
self.value = x
self.next = None
class Solution:
#@param a ListNode
#@return a ListNode
def swapPairs(self, head):
if head != None and head.next != None:
next = head.next
head.next = self.swapPairs(next.next)
next.next = head
return next
return head
7、创建字典方法
工厂方法
items = [('name','earth'), ('port','80')]
dict2 = dict(items)
fromkeys()方法
dict1 = {}.fromkeys(('x', 'y'),-1)
8、合并两个有序列表
合并排序O(nlogn)
list1 = [33, 37, 38, 39]
list2 = [35, 36, 40, 43, 45, 50]
尾递归
def _recursion_merge_sort(list1, list2, tmp):
if len(list1) == 0 or len(list2) == 0:
tmp.extend(list1)
tmp.extend(list2)
return tmp
else:
if list1[0] <list2[0]:
tmp.append(list1[0])
del list1[0]
else:
tmp.append(list2[0])
del list2[0]
return _recursion_merge_sort(list1, list2, tmp)
def recursion_merge_sort(list1, list2):
tmp = _recursion_merge_sort(list1, list2,[])
return tmp
循环
def loop_merge_sort(list1, list2):
result = []
while list1 and list2:
if list1[0] <= list2[0]:
result.append(list1[0])
del list1[0]
else:
result.append(list2[0])
del list2[0]
if list1 == []:
result.extend(list2)
if list2 == []:
result.extend(list1)
return result
9、交叉链表求交点
其实思想可以按照从尾开始比较两个链表,如果相交,则从尾开始必然一致,只要从尾开始比较,直至不一致的地方即为交叉点。
a = [1,2,3,7,9,1,5]
b = [4,5,7,9,1,5]
for i in range(1, min(len(a),len(b))):
if i== 1 and (a[-1] != b[-1]):
print('No')
break
else:
if a[-i] != b[-i]:
print('交叉节点:', a[-i+1])
break
#构造链表类
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
#求出链表长度的差值,长链表的指针先想后移动lenA-lenB。
#然后两个链表一起往后走,若结点相同则第一个相交点
def node(l1, l2):
len1, len2 = 0, 0
#求两链表长度
while l1.next:
l1 = l1.next
len1 += 1
while l2.next:
l2 = l2.next
len2 += 1
#如果相交
if l1.next == l2.next:
#长链表先走
if len1 > len2:
for _ in range(len1 - len2):
l1 = l1.next
return l1
else:
for _ in range(len2-len1):
l2 = l2.next
return l2
else:
return
10、二分查找
O(logn)
def binary_search(list, item):
low = 0
high = len(list) - 1
while low <= high:
middle = int((low + high)/2)
guess = list[middle]
if guess > item:
high = middle - 1
elif guess < item:
low = middle + 1
else:
return middle
return 'Not Found'
# 排序列表
orded_list = [1,3,4,5,6,7,8,9,11]
print(binary_search(orded_list,3))
#补充:
l = [3,7,9,6,4,8,11,1,5]
l = sorted(l)
11、快速排序
O(nlogn)
def quick_sort(list):
if len(list) < 2:
return list
else:
middle = list[0]
lessbeforemiddle = [x for x in list[1:] if x <= middle]
largebefoemiddle = [x for x in list[1:] if x > middle]
finally_list = quick_sort(lessbeforemiddle) + [middle] + quick_sort(largebefoemiddle)
return finally_list
quick_sort(l)
12、冒泡排序
O(n^2)
def swap(l, i, j): #交换
t = l[i]
l[i] = l[j]
l[j] = t
def bubble_sort(list):
n = len(list)
while n > 1:
i = 1
while i < n:
if list[i-1] > list[i]:
swap(list, i ,i-1)
i += 1
n -= 1
13、广度优先搜索
O(节点数+边数)
graph = {}
graph["you"] = ["alice",'bob',"calm"]
graph["alice"] = ["peggym"]
graph["bob"] = ["anuj","peggym"]
graph["peggym"] = ["anuj"]
graph["anuj"] = ["peggym"]
# print type(graph)
from collections import deque
def person_is_seller(person):
if 'm' in person:
return person
def search(name):
search_queue = deque()
search_queue += graph[name]
searched = []
while search_queue:
person = search_queue.popleft()
if person not in searched:
if person_is_seller(person):
print(person + 'is seller')
searched.append(person)
esle:
search_queue += graph[person]
searched.append(person)
return False
search('you')
14、动态规划———找零问题
#values是硬币的面值values = [ 25, 21, 10, 5, 1]
#valuesCounts 钱币对应的种类数,5
#money 总钱数,63
#coinsUsed 对应于目前钱币总数i所使用钱币数目
def coin_change(values, valuesCounts, money, coinsUsed):
for i in range(1, money + 1):
minValue = i
for num in range(valuesCounts):
if values[num] <= i:
count = coinsUsed[i - values[num]] + 1
if count < minValue:
minValue = count
coinsUsed[i] = minValue
print('第%d 最少需要 %d 枚钱币' %(i, minValue))
if __name__ == '__main__':
# values = [25, 21, 10, 5, 1]
money = 63
values = [1,2,5,7,9,20]
coinsUsed = [0]*(money + 1)
length = len(values)
coin_change(values, length, money, coinsUsed)
15、二叉树节点
class Node(object):
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
tree = Node(1, Node(3, Node(7, 0), 6), Node(2, 5, 4)
网友评论