- 二分查找
#coding=utf-8
def binary_search(list, item):
low = 0
high = len(list) - 1
while low <= high: # While you haven't narrowed it down to one element ...
mid = (low + high) // 2 # ... check the middle element
guess = list[mid]
if guess == item:
return mid
if guess > item:
high = mid - 1
else:
low = mid + 1
return None # Item dosen't exist
my_list = [1, 3, 5, 7, 9]
print (binary_search(my_list, 3)) # 'None' means nil in Python. We use to indicate that the item wasn't found.
2.选择排序
#coding=utf-8
# Finds the smallest value in an array
def findSmallest(arr):
smallest = arr[0] # Stores the smallest value
smallest_index = 0 # Stores the index of the smallest value
for i in range(1, len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index
def selectionSort(arr):
newArr = []
for i in range(len(arr)):
# Finds the smallest element in the array and adds it to the new array
smallest = findSmallest(arr)
newArr.append(arr.pop(smallest))
return newArr
print(selectionSort([5, 3, 6, 2, 10]))
3.递归
3.1 基线条件 和 递归条件
#coding=utf-8
# 基线条件和递归条件
def countdown(i):
if i <= 0: # <---- base case 基线条件
return
else:
countdown(i-1) # <---- recursive case 递归条件
countdown(5)
3.2 调用栈
这是本节的一个重要概念:调用另一个函数时,当前函数暂停并处于未完成状态
# 调用栈
def greet2(name):
print("how are you, " + name + "?")
def bye():
print("ok bye!")
def greet(name):
print("hello, " + name + "!")
greet2(name)
print("getting ready to say bye...")
bye()
greet("adit")
3.3 递归调用栈-斐波那契
def fact(x):
if x == 1:
return 1
else:
return x * fact(x-1)
print(fact(5))
4.快速排序
快速排序闭选择排序快很多。
使用了分而治之(D&C)思想。
别忘了,你要使用D&C,因此需要将数组分解,直到满足基线条件
def quickSort(array):
if len(array) < 2:
return array # 基线条件:为空或只包含一个元素的数组是“有序”的
else:
pivot = array[0] # 递归条件
less = [i for i in array[1:] if i <= pivot ] # 由所有小于基准值的元素组成的子数组
greater = [i for i in array[1:] if i > pivot ] # 由所有大于基准值的元素组成的子数组
return quickSort(less) + [pivot] + quickSort(greater)
print(quickSort([10, 5, 2, 3]))
5 散列表
散列表由键和值组成
对于同样的输入,散列表必须返回同样的输出,这一点很重要
使用散列表来检查是否重复,速度非常快
6.广度优先搜索
#coding=utf-8
from collections import deque
# 判断一个人是不是芒果销售商
def person_is_seller(name):
return name[-1] == 'm' # 检查人的姓名是否以m结尾
graph = {}
graph["you"] = ["alice", "bob", "claire"]
graph["bob"] = ["anuj", "peggy"]
graph["alice"] = ["peggy"]
graph["claire"] = ["thom", "jonny"]
graph["anuj"] = []
graph["peggy"] = []
graph["thom"] = []
graph["jonny"] = []
def search(name):
search_queue = deque() # 创建一个队列
search_queue += graph[name] # 将你的邻居都加入到这个搜索队列中
searched = [] # 这个数组用于记录检查过的人
while search_queue: # 只要队列不为空
person = search_queue.popleft() # 就取出其中的第一个人
if not person in searched: # 仅当这个人没检查过时才检查
if person_is_seller(person): # # 检查这个人是否是芒果销售商
print(person + " is a mango seller!") # 是芒果销售商
return True
else:
search_queue += graph[person] # 不是芒果销售商。将这个人的朋友都加入搜索队列
searched.append(person) # 将这个人标记为检查过
return False # 如果到达了这里,就说明队列中没人是芒果销售商
print(search("you"))