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实现关联规则 ...
随机推荐
- Js极客之路 - 优化操作(性能优化)
1.因为每次For循环都会计算一次arr.length,所以有必要存储数组长度以减少计算.针对这篇文章(http://www.crimx.com/2015/04/21/should-array-len ...
- Java 在PDF中添加页面跳转按钮
在PDF 中可通过按钮来添加动作跳转到指定页面,包括跳转到文档首页.文档末页.跳转到上一页.下一页.或跳转到指定页面等.下面将通过java代码来演示如何添加具有以上几种功能的按钮. 使用工具: Fre ...
- day10作业(函数实现注册''')
在猜年龄的基础上编写登录.注册方法,并且把猜年龄游戏分函数处理,如 登录函数 注册函数 猜年龄函数 选择奖品函数 '''在猜年龄的基础上编写登录.注册方法,并且把猜年龄游戏分函数处理,如 2. 登录函 ...
- Java网络编程(二)IP、URL和HTTP
一.IP InetAddress类有一些静态工厂方法,可以连接到DNS服务器来解析主机名. 示例1:InetAddress address = InetAddress.getByName(" ...
- Dubbo配合SpringBoot,实现接口多个实现(group)
SpringBoot配合Dubbo,使用@Service和@Reference,group实现接口多实现 公司项目升级,需要实现springBoot + Dubbo,并支持一个接口多个实现的情况.遇到 ...
- mysql实现海量数据的存储、访问的解决方案
mysql实现海量数据的存储.访问的解决方案: mysql数据库水平切分的实现原理可分为以下几个:分库,分表,主从,集群,负载均衡器等 第1章 引言 随着互联网应用的广泛普及,海量数据的存储和访问成为 ...
- SVM详细笔记及总结
本文精品,如有疑问欢迎留言or微信咨询:523331232
- spring cloud 2.x版本 Zuul路由网关教程
前言 本文采用Spring cloud本文为2.1.8RELEASE,version=Greenwich.SR3 本文基于前两篇文章eureka-server.eureka-client.eureka ...
- pythonpip的基本使用
pip 是 Python 包管理工具,该工具提供了对Python 包的查找.下载.安装.卸载的功能.目前如果你在 python.org 下载最新版本的安装包,则是已经自带了该工具.Python 2.7 ...
- Numpy 中的聚合操作
# 导包 import numpy as np sum np.random.seed(10) L = np.random.random(100) sum(L) np.sum(L) min np.min ...