Python算法——《算法图解》笔记
算法目录
二分查找
大O表示法
选择排序
递归
快速排序,分而治之(D&C)
散列表——字典
广度优先搜索——BFS
Dijkstra算法
贪婪算法
二分查找
# 要求list是有序表,num是要查找的数字
# 二分查找貌似只能查找数值表
def binary_search(list, num):
low = 0
high = len(list) - 1 # 因为python数组(列表)是从0开始索引的 while low <= high:
mid = (low + high)
guess = list[mid]
if guess == num:
return "found it is " + str(mid)
if guess > num:
high = mid - 1
else:
low = mid + 1
return "not found" # python数组不同于matlab数组,python中间要用逗号隔开,而matlab不用
my_list = [1, 3, 5, 7, 9, 11, 13]
print(binary_search(my_list, 6))
print(binary_search(my_list, 9))
大O表示法
选择排序
寻找数组中的最小值的索引
def find_smallest_index(arr):
smallest = arr[0]
smallest_index = 0;
# python中检查数组长度的函数是len,而matlab中是length
for i in range(1, len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index # 对数组进行排序
def selection_insort(arr):
# create new array
new_arr = []
for i in range(len(arr)):
smallest_index = find_smallest_index(arr)
# array.pop()只能根据索引值弹出元素,so pop()应传入索引值
new_arr.append(arr.pop(smallest_index))
return new_arr mess_arr = [3, 1, 9, 2, 5, 4]
print("This is uninsort array: " + str(mess_arr))
insorted_arr = selection_insort(mess_arr)
print("This is insorted array: " + str(insorted_arr))
递归
# 一个计算数学阶乘的递归调用
def func(x):
if x == 1:
return 1
else:
return x * func(x-1) print(func(3)) #一个计算数组和的递归调用
def func(arr):
if arr == []:
return 0
else:
# 这里不能用arr[0] + func()因为基线条件是arr==[]当arr
# 只有一个元素时python会将arr变为一个int数值,而不会是数组
return arr.pop() + func(arr) arr = [2, 3, 4]
print(func(arr))
快速排序,分而治之(D&C)
# 快速排序——by myself
def quickly_sort(arr):
# 两个基线条件
if len(arr) < 2:
return arr
# 直接选取数组元素第一个当作基准值——递归条件
reference_value = arr[0]
larger_arr = []
smaller_arr = []
for i in range(1,len(arr)):
if arr[i] > reference_value:
larger_arr.append(arr[i])
# arr.pop(i)
else:
smaller_arr.append(arr[i])
# arr.pop(i)
return quickly_sort(smaller_arr) + [reference_value] + quickly_sort(larger_arr) mess_arr = [3, 1, 9, 2, 5, 4]
print("This is uninsort array: " + str(mess_arr))
insorted_arr = quickly_sort(mess_arr)
print("This is insorted array: " + str(insorted_arr))
# 快速排序——by others
def quickly_sort(arr):
# 基线条件
if len(arr) < 2:
return arr
else:
# 选取基准值——递归条件
pivot = arr[0] # 简洁明了选出较大数组与较小数组
larger = [i for i in arr[1:] if i > pivot]
smaller = [i for i in arr[1:] if i <= pivot]
# 递归调用
return quickly_sort(smaller) + [pivot] + quickly_sort(larger) mess_arr = [3, 1, 9, 2, 5, 4]
print("This is uninsort array: " + str(mess_arr))
insorted_arr = quickly_sort(mess_arr)
print("This is insorted array: " + str(insorted_arr))
散列表——字典
# 散列表——字典
# 创建字典的两种方案
price_list = dict()
price_list = {} # 添加数据
price_list["apple"] = 0.67
price_list["milk"] = 1.49
price_list["bread"] = 0.49 print(price_list)
print(price_list.keys())
print(price_list.values())
print(price_list.items()) # 判断是否在散列表中
flag = price_list.get("apple")
print(flag)
# 不同大小写诗不同与阿奴
flag = price_list.get("Apple")
print(flag)
flag = price_list.get("banana")
print(flag)
广度优先搜索——BFS
# 广度优先搜索示例
from collections import deque # 创建一个关系图(散列表)
graph = {}
# 单引号与双引号基本无使用上的区别,但是三引号可实现跨行输出
graph["you"] = ["alice", 'bob', "claire"]
graph["alice"] = ['peggy']
graph["bob"] = ["anuj", 'peggy']
graph['claire'] = ["thom", 'jonny']
graph["peggy"] = []
graph["anuj"] = []
graph["thom"] = []
graph["jonny"] = [] search_queue = deque()
search_queue += graph["you"] # 判断是否为经销商
def person_is_seller(name):
return (name[-1] == 'o') def search(search_queue):
searched = []
while search_queue: person = search_queue.popleft() #取出队列左边第一个元素
# 检查后不再检查
if person not in searched:
if person_is_seller(person):
print(person + " is a mago seller !")
return True
else:
# 把TA的朋友加入搜索队列
search_queue += graph[person]
searched.append(person)
print("Can't find mago seller in your friends")
return False
search(search_queue)
Dijkstra算法
# Dijkstra算法 # 寻找lowest_cost_node
def find_lowest_cost_node(costs):
lowest_cost = float("inf")
lowest_cost_node = None
for node in costs:
cost = costs[node]
if cost < lowest_cost and node not in processed:
lowest_cost = cost
lowest_cost_node = node
return lowest_cost_node # Create a graph
graph = {}
graph['start'] = {}
graph['start']['a'] = 6
graph['start']['b'] = 2
graph['a'] = {}
graph['a']['fin'] = 1
graph['b'] = {}
graph['b']['fin'] = 5
graph['b']['a'] = 3
graph['fin'] = {} # create a cost dict
infinity = float('inf')
costs = {}
costs['a'] = 6
costs['b'] = 2
costs['fin'] = infinity # creata a parent dict
parents = {}
parents['a'] = "start"
parents['b'] = "start"
parents['fin'] = None # record processed nodes
processed = [] node = find_lowest_cost_node(costs)
while node is not None:
cost = costs[node]
neighbors = graph[node]
for n in neighbors.keys():
new_cost = cost + neighbors[n]
if costs[n] > new_cost:
costs[n] = new_cost
parents[n] = node
processed.append(node)
node = find_lowest_cost_node(costs) route = ['fin']
node = parents['fin']
route.append(node)
node = parents[node]
route.append(node)
node = parents[node]
route.append(node) print(route)
贪婪算法
Python算法——《算法图解》笔记的更多相关文章
- python聚类算法实战详细笔记 (python3.6+(win10、Linux))
python聚类算法实战详细笔记 (python3.6+(win10.Linux)) 一.基本概念: 1.计算TF-DIF TF-IDF是一种统计方法,用以评估一字词对于一个文件集或一个语料库 ...
- Python基础算法综合:加减乘除四则运算方法
#!usr/bin/env python# -*- coding:utf-8 -*-#python的算法加减乘除用符号:+,-,*,/来表示#以下全是python2.x写法,3.x以上请在python ...
- xsank的快餐 » Python simhash算法解决字符串相似问题
xsank的快餐 » Python simhash算法解决字符串相似问题 Python simhash算法解决字符串相似问题
- Python 基础算法
递归 时间&空间复杂度 常见列表查找 算法排序 数据结构 递归 在调用一个函数的过程中,直接或间接地调用了函数本身这就叫做递归. 注:python在递归中没用像别的语言对递归进行优化,所以每一 ...
- python排序算法实现(冒泡、选择、插入)
python排序算法实现(冒泡.选择.插入) python 从小到大排序 1.冒泡排序: O(n2) s=[3,4,2,5,1,9] #count = 0 for i in range(len(s)) ...
- Python机器学习算法 — 关联规则(Apriori、FP-growth)
关联规则 -- 简介 关联规则挖掘是一种基于规则的机器学习算法,该算法可以在大数据库中发现感兴趣的关系.它的目的是利用一些度量指标来分辨数据库中存在的强规则.也即是说关联规则挖掘是用于知识发现,而非预 ...
- Python C3 算法 手动计算顺序
Python C3 算法 手动计算顺序 手动计算类继承C3算法原则: 以所求类的直接子类的数目分成相应部分 按照从左往右的顺序依次写出继承关系 继承关系第一个第一位,在所有后面关系都是第一个出现的 ...
- python聚类算法解决方案(rest接口/mpp数据库/json数据/下载图片及数据)
1. 场景描述 一直做java,因项目原因,需要封装一些经典的算法到平台上去,就一边学习python,一边网上寻找经典算法代码,今天介绍下经典的K-means聚类算法,算法原理就不介绍了,只从代码层面 ...
- python相关性算法解决方案(rest/数据库/json/下载)
1. 场景描述 一直做java,因项目原因,需要封装一些经典的算法到平台上去,就一边学习python,一边网上寻找经典算法代码,今天介绍下经典的相关性算法,算法原理就不介绍了,只从代码层面进行介绍,包 ...
- 关联规则 -- apriori 和 FPgrowth 的基本概念及基于python的算法实现
apriori 使用Apriori算法进行关联分析 貌似网上给的代码是这个大牛写的 关联规则挖掘及Apriori实现购物推荐 老师 Apriori 的python算法实现 python实现关联规则 ...
随机推荐
- 使用 pdf.js 在网页中加载 pdf 文件
在网页中加载并显示PDF文件是最常见的业务需求.例如以下应用场景:(1)在电商网站上购物之后,下载电子发票之前先预览发票.(2)电子商务管理系统中查看发布的公文,公文文件一般是PDF格式的文件. 目前 ...
- 设置H5页面文字不可复制
* { moz-user-select: -moz-none; -moz-user-select: none; -o-user-select: none; -khtml-user-select: no ...
- Linux常用命令(1)
常用命令(1) 1.系统相关命令 su 切换用户 hostname 查看主机名 who 查看登录到系统的用户 whoami 确认自己身份 history 查看运行命令的历史 ifconfig ...
- 微服务SpringCloud之服务网关zuul二
Zuul的核心 Filter是Zuul的核心,用来实现对外服务的控制.Filter的生命周期有4个,分别是“PRE”.“ROUTING”.“POST”.“ERROR”,整个生命周期可以用下图来表示. ...
- SpringBoot整合MybatisPlus3.X之分页插件(四)
注:详细请看2.X博客中,3.X直接上代码. 建议装一个MybatisX插件,可以在Mapper和Xml来回切换 pom.xml <dependencies> <dependency ...
- SpringCloud配置中心集成Gitlab(十五)
一 开始配置config服务 config-server pom.xml <dependency> <groupId>org.springframework.cloud< ...
- 完美解决Python与anaconda之间的冲突问题
anaconda指的是一个开源的Python发行版本,其包含了conda.Python等180多个科学包及其依赖项.因为包含了大量的科学包,Anaconda 的下载文件比较大(约 515 MB),如果 ...
- kali linux 开启配置ssh服务
1. 一.配置SSH参数 修改sshd_config文件,命令为: vi /etc/ssh/sshd_config 将#PasswordAuthentication no的注释去掉,并且将NO修 ...
- 使用koa-mysql-session时报错
描述 在本地测试代码没问题,但是部署到服务器上时就报错. 错误 > cross-env WEBPACK_TARGET=node NODE_ENV=production node ./server ...
- tracert/traceroute原理
一.路由追踪程序traceroute/tracert Traceroute是Linux和Mac OS等系统默认提供的路由追踪小程序,Tracert是Windows系统默认提供的路由追踪小程序.二者的功 ...