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实现关联规则 ...
随机推荐
- NOMP矿池搭建
本文将以dash(x11)和Raven(x16rv2)为例子来说明多算法矿池的搭建过程. 1 环境准备 1.1 准备Ubuntu 准备虚拟机或物理机,操作系统为Ubuntu 16.04 1.2 安装必 ...
- office visio 2019 下载激活
安装 下载 office ed2k://|file|cn_office_professional_plus_2019_x86_x64_dvd_5e5be643.iso|3775004672|1E4FF ...
- ElasticSearch - ElasticSearch和kinaba的简单使用
ElasticSearch和kinaba的简单使用 ElasticSeatch 文档推荐 ElasticSearch 下载 (端口 9200) 安装好es,可以访问 http://localhost: ...
- springboot整合Shiro功能案例
Shiro 核心功能案例讲解 基于SpringBoot 有源码 从实战中学习Shiro的用法.本章使用SpringBoot快速搭建项目.整合SiteMesh框架布局页面.整合Shiro框架实现用身份认 ...
- 设计模式(十五)Facade模式
Facade模式可以为相互关联在一起的错综复杂的类整理出高层接口,可以让系统对外只有一个简单的接口,而且还会考虑到系统内部各个类之间的责任关系和依赖关系,按照正常的顺序调用各个类. 还是先看一下示例程 ...
- linux centos ubutun svn搭建
1.卸载SVN 查看自己是否安装了svn svn 上图显示已安装,可用以下命令进行卸载 sudo apt-get remove --purge subversion (–purge 选项表示彻底删除改 ...
- Codeforces 游记
早就对这个比赛平台有所耳闻(事实上,之前打过一场div2惨的一批……)今天去打了一场div3. 首先还是吐槽一下这个毛子时区的比赛时间,从十点三十五到零点三十五……这种时间要不是在家根本没法打嘛…… ...
- [考试反思]0807NOIP模拟测试14:承认
一大排并列Rank#9之一. 考试题还没改完(而且并不会模拟退火)所以题解又只能咕了 然而并不想吐槽T2对sjzyz是原题导致4个AC里面有3个他们的 虽说这次的成绩不怎么样,但是这次的考试过程是全新 ...
- CSPS模拟 89
- 「Luogu 1349」广义斐波那契数列
更好的阅读体验 Portal Portal1: Luogu Description 广义的斐波那契数列是指形如\(an=p \times a_{n-1}+q \times a_{n-2}\)的数列.今 ...