Python Algorithms Learning Notes(2)—Implementing Graphs and Trees

Pandas入门教程(二十二):股票数据分析实战——yfinance 获取数据、技术指标与收益率分析 把 Pandas 用在真实场景,才能体会它的价值。本文以茅台股票为例,用 yfinance 获取历史行情,完成缺失值处理与列筛选,绘制收盘价曲线,计算 SMA 移动平均线与 RSI 相对强弱指数,并通过日收益率、累计收益率和波动率完成完整的量化分析流程。 阅读详情

It’s been a week since last time I read Python Algorithms ,time flies. There are always so many errands keeping me from reading a tech book constantly.
I think keeping notes in blog helps drive me to continue .
One thing bothers me though ,I’m not sure about the language mistakes I made in blogs ,which I believe must be a lot.
I dont’t know how to check out all my mistakes to improve.
And I might end up writing my own ‘freestyle’ English ,without any real progress.


Anyway,today I’m reading about Graphs anf Trees.


1.Graphs

1.1 Basic Concepts

Graphs are one of the most powerful frameworks in algorithms.
Graphs can represent all kinds of strctures and systems we may encounter solving algorithmic problems.

A graph G=(V,E) consists of a set of nodes ,V, and edges E between them.
If the edges have a direction ,we say the graph is directed.
If we associate a weight with each edge in G , we say G is a weighted graph

A forest is a cycle-free graph, a connected graph is a tree

BLACK BOX
Hashing is used in the machanism of dictionaries and sets
Accessing elements of a dict or set can be assumed to take constant time ,basically,Θ(1) in average

1.2 Implementing of graphs

(1)Adjacency lists and the like

Basically, for each node,
we can access a list (or set or other container or iterable) of its neighbors。

Let’s take the simplest way of implementing this, assuming we have n nodes, numbered 0…n–1.
GraphSample

Method1. A straightforward Adjaceny Set Representation

a,b,c,d,e,f,g,h = range(5)
N = [
{b, c, d, e, f}, # a
{c, e},          # b
{d},             # c
{e},             # d
{f},             # e
{c, g, h},       # f
{f, h},          # g
{f, g}           # h
]      

N[v] is now a set of v’s neighbors.

>>>b in N[a]    # Neighborhood membership
True
>>> len(N[f])    # Degree
3

Method 2. Adjacency Lists

a, b, c, d, e, f, g, h = range(8)
N = [
[b, c, d, e, f],      # a
[c, e],               # b
[d],                  # c
[e],                  # d
[f],                  # e
[c, g, h],            # f
[f, h],               # g
[f, g]                # h
]

Replace the adjacency sets with adjacency lists.
The membership checking is now Θ(n),which is a significant slow down.
But it’s useful and neccessary if we need to iterate over neighbors and the like.

Method3.Adjacency dicts with Edge Weights

a, b, c, d, e, f, g, h = range(8)
N = [
{b:2, c:1, d:3, e:9, f:4},   # a
{c:4, e:3},                  # b
{d:8},                       # c
{e:7},                       # d
{f:5},                       # e
{c:2, g:2, h:2},             # f
{f:1, h:6},                  # g
{f:9, g:8}                   # h
]

The adjacency dict version can be used just like the others, with the additional edge weight functionality :

>>> b in N[a]   # Neighborhood membership
True
>>> len(N[f])   # Degree
3
>>> N[a][b]   # Edge weight for (a, b)
2

Method4.A Dict with Adjacency Sets
A more flexible approach (allowing us to use arbitrary,hashable, node labels) is to use a dict as this main structure.

N = {
'a': set('bcdef'),
'b': set('ce'),
'c': set('d'),
'd': set('e'),
'e': set('f'),
'f': set('cgh'),
'g': set('fh'),
'h': set('fg')
}

Note that nodes are now represented by characters.

(2)Adjacency Matrices

Instead of listing all neighbors for each node, we have one row (an array) with one position for each possible neighbor (that is, one for each node in the graph), and store a value (such as True or False),indicating whether that node is indeed a neighbor.

Method1.An Adjacency Matrix, Implemented with Nested Lists

a, b, c, d, e, f, g, h = range(8)
# a b c d e f g h
N = [[0,1,1,1,1,1,0,0], # a
[0,0,1,0,1,0,0,0], # b
[0,0,0,1,0,0,0,0], # c
[0,0,0,0,1,0,0,0], # d
[0,0,0,0,0,1,0,0], # e
[0,0,1,0,0,0,1,1], # f
[0,0,0,0,0,1,0,1], # g
[0,0,0,0,0,1,1,0]] # h

The way we’d use this is slightly different from the adjacency lists/sets.

>>> N[a][b] # Neighborhood membership
1
>>> sum(N[f]) # Degree
3

Method2.A Weight Matrix with Infinite Weight for Missing Edges

a, b, c, d, e, f, g, h = range(8)
_ = float('inf')
# a b c d e f g h
W = [[0,2,1,3,9,4,_,_], # a
[_,0,4,_,3,_,_,_], # b
[_,_,0,8,_,_,_,_], # c
[_,_,_,0,7,_,_,_], # d
[_,_,_,_,0,5,_,_], # e
[_,_,2,_,_,0,2,2], # f
[_,_,_,_,_,1,0,6], # g
[_,_,_,_,_,9,8,0]] # h

Weight matrices make it easy to access edge weights, of course, but membership checking and finding the degree of a node, for example, or even iterating over neighbors must be done a bit differently now. You need to take the infinity value into account–for example, like this (using inf = float(‘inf’) for more readable code)

>>> W[a][b] < inf # Neighborhood membership
True
>>> W[c][e] < inf # Neighborhood membership
False
>>> sum(1 for w in W[a] if w < inf) - 1 # Degree
5

Note that 1 is subtracted from the degree sum, because we don’t want to count the diagonal.
Thedegree calculation here is Θ(n), whereas both membership and degree could easily be found in constant time with the proper structure.
Again, you should always keep in mind how you are going to use your graph and represent it accordingly


2.Trees

Trees are just a special kind of graphs, so most algorithms and
representations for graphs will work for them as well.
However, because of their special properties (they are connected and have no cycles),
some specialized (and quite simple) versions of both the representations and algorithms are possible.

2.1 Implementing trees

treesample

Method1.represent that tree with lists of lists

>>> T = [[“a”, “b”], [“c”], [“d”, [“e”, “f”]]]
>>> T[0][1]
‘b’
>>> T[2][1][0]
‘e’

Each list is, in a way, a neighbor (or child) list of the (anonymous) internal nodes.
In the second example, we access the third child of the root, the second child of that child, and finally the first child of that (path highlighted in the figure).

Method2.A Binary Tree Class
A binary tree is one where each internal node has a maximum of two children.

class Tree:
    def __init__(self, left, right):
        self.left = left
        self.right = right

You can use the Tree class like this:

>>> t = Tree(Tree(“a”, “b”), Tree(“c”, “d”))
>>> t.right.left
‘c

Method3.A Multiway Tree Class
A common way of implementing trees, especially in languages that don’t have built-in lists, is the first child, next sibling representation.

Each tree node refers to a linked list of siblings (its children), and each of these siblings refers to a linked list of its own.

class Tree:
    def __init__(self, kids, next=None):
        self.kids = self.val = kids
        self.next = next

Here’s an example of how you can access this structure:

>>> t = Tree(Tree(“a”, Tree(“b”, Tree(“c”, Tree(“d”)))))
>>> t.kids.next.next.val
‘c’

And here’s what that tree looks like:
tree2


Postscript
I copied a lot directly from the book. And I feel it’s really not easy to summarize my own unique conclusion with this kind of mature topic.
I guess I should concentrate more on the specific implemention methods , and ignore those theoretical details .I don’t really have that much time.
Fighting~!

Reference
《Python Algorithms》by Magnus Lie Hetland.

如何处理动态语言(Python / JS)的“隐形”调用链? 本文揭示动态语言(Python/JS)中静态AST解析导致调用链“断链”的核心问题,提出通过运行时追踪补全图谱的解决方案。基于Code-Graph-RAG的cgr trace机制,分别利用pytest插件与V8 Profiler捕获真实调用路径,将动态边合并至静态图谱,并在权重体系中提升动态边优先级。实践表明,该方法可显著提升图谱覆盖率,实现“结构+行为”双视角理解代码,为MCP与Rerank系统提供可靠支持。 阅读详情

相关推荐

薅“刷宝”羊毛的autojs脚本教程,简单粗暴好用!!!

本教程旨在帮助大家实现用手机或闲置手机来进行“刷宝”平台的收益,能薅多少米就看你的本事了,作者教你的是如何用autojs来进行脚本的挂机教程,掌握了这个思路后,你可以根据自己的实际需要来改进脚本或者撸别的平台:) 适用系统,**android4.0以上,苹果机暂不适用**(大多数android系统手机都是7.0以上,要查看自己手机是android几,见文件夹“视频教程-基础”>1.查看android版本的方法)

rousseaou8的博客 8万+

CNN笔记(6)---超参数设定和网络训练

11.超参数设定和网络训练 11.1 网络超参数设定 网络结构相关的各项超参数:输入图像像素、卷积层个数、卷积核的相关参数 11.1.1 输入数据像素大小 不同输入图像为得到同规格输出,统一压缩到2n2n2^n大小:32x32,96x96,224x224 分辨率越高,有助于性能提升,(特别是attention model),但是会延长训练时间 改变原始模型的输入图像分辨率,需要重...

CodenameNC的博客 1万+

机器学习西瓜书期末复习(2022HENU)

期末复习之机器学习 文章目录期末复习之机器学习第一章 绪论 第一章 绪论 机器学习的定义 机器学习致力于研究如何通过计算的手段,利用经验来改善系统自身的性能。 根据训练数据是否拥有标记信息,将学习任务分为监督学习和无监督学习。 监督学习 :分类和回归 线性回归、对数几率回归、决策树、支持向量机、贝叶斯分类器、神经网络 无监督学习:聚类 聚类算法: 原型聚类:(k均值,学习向量量化,高斯混合聚类);密度聚类(DBSVAN);层次聚类(AGNES)。降维。话题分析。图分

qq_46561559的博客 2万+

高斯混合模型视频背景建模的EM算法与Matlab 实现

使用 混合高斯模型 对视频背景进行建模,实现视频的背景前景分离; 使用 EM 算法迭代估计混合高斯模型参数; 使用Matlab 实现整个视频动静分离过程。

CodenameNC的博客 8672

【新手流程】1小时解决Anaconda+Cuda+Cudnn+Pytorch+Pycharm深度学习环境配置

一小时速通Anaconda+Cuda+Cudnn+Pytorch+Pycharm环境配置

m0_57190453的博客 4088

PCB之AD层次化原理图设计

PCB之AD层次化(模块化)原理图设计 软件版本:AD17.1.9(bBuild 592) 先上效果图: 可以看到,图中有RS485和W5500这两个部分是复用了原理图,当项目中需要多个功能相同的电路时,这种设计就可以大大节约PCB布局布线的时间,方法后面介绍; 1.首先确定好项目中个部分电路的功能模块 不同功能的电路分开不同原理图画,然后给出输入输出端口,这样方便复用,下面是实例项目的功能划分 2.单个模块电路的接口设计 这里以W5500以太网接口电路为例说明: 主要就分为通讯接口和电源接口:

洋洋洋的博客 3万+

CNN笔记(7)---不平衡数据的处理(imbalance)

12.不平衡数据的处理(imbalance) 除了常规的分类,回归任务,图像语义分割,深度估计等像素级别任务也不乏不平衡样本的出现 12.1 数据层面处理方法 数据层面处理方法多借助数据采样法(sampling)使整体训练集样本趋于平衡 即各类样本数基本一致 12.1.1 数据重采样 重采样包括上采样和下采样 对于样本较少的类别,使用上采样(赋值/数据扩充),增加样本数 对...

CodenameNC的博客 7577

cefsharp139-H264-X86升级测试(MP4)-支持PDF预览-chromium7258定制浏览器

CEFSharp 139.x版本升级测试已完成,该版本支持64位系统(需选择x86架构)及WinForms.NETCore(.NET8)。升级内容包括H264文件编译支持Mp4播放,并覆盖WPF、WinForms等平台。文中提供了版本替换方法及不同系统的版本建议(如Win10/11推荐111/133/134/139版)。此外,文章还列举了CEFSharp的多种应用场景,包括浏览器开发、B/S系统封装、资源抓取等,同时指出当前版本均需自行编译以支持MP4播放。详细图文说明及旧版链接已附在正文中。

无线智能模块 可视DIY智能专家 1301

CNN学习笔记(5)---正则化

10.Regularization 正则化有效防止模型的过拟合 10.1 l2l2l_2正则化 —邻回归(Ridge regression)—Tikhonov 正则化 假设待正则的网络层参数为www,l2l2l_2正则式为: l2=12λ||w||22l2=12λ||w||22 l_2 = \frac{1}{2}\lambda ||w||^2_2 将正则项加入目标函数 又叫...

CodenameNC的博客 6804

【明道云】如何让用户可以新增但不能修改记录

在设计表单时直接将字段设置只读是不行的。字段设置只读将会直接让界面上此字段的前端组件不可编辑。

每日出拳老爷子的博客 701

手把手教你学Simulink--基于微电网的建模与仿真场景实例:独立运行模式下微电网的能量管理系统设计

本文详细介绍了使用Simulink对独立运行微电网能量管理系统进行建模与仿真的完整流程。主要包括:系统结构设计(分布式能源、储能系统、负荷等模块)、建模步骤(从创建项目到实现能量管理策略)、仿真设置与结果分析。通过建立基于规则的控制逻辑和优化调度算法,实现微电网的自主运行和能量优化管理。文章还提供了参数优化和多目标改进建议,为新能源和智能电网领域的研究与应用提供了实用指导。

MHD0815的博客 8584

SVM分类器的概率校准在scikit-learn 中的几种实现方式

SVM分类器的分类结果只有类别,没有概率,属于maximum-margin 的方法 如果我们想从SVM的分类结果中得到属于某个类别的置信概率,就要用到 概率校准 经典的概率校准思路有Platt Scaling,核心思想就是把分类的结果作为新的训练集,用logistics回归再训练一个关系,得到具体的概率值 P(y=1∣x)=11+e(A∗f(x)+B)P(y=1∣x)=11+e(A∗f(...

CodenameNC的博客 6144

【STK】手把手教你利用STK进行光电红外仿真03-STK/EOIR模块属性之二 导弹等目标的EOIR设置

上一节介绍了如何设置传感器的通用属性和空间、光学、光谱、辐射四种专项属性。这一节介绍如果对导弹等目标的EOIR属性进行修改。

weixin_44184852的博客 2204

CNN学习笔记(8)---模型集成方法

13.模型集成方法 深度模型的集成多从“数据层面”和“模型层面”两方面着手 13.1 数据层面的集成方法 13.1.1 测试阶段数据扩充 训练阶段的数据扩充手段:图像多尺度,随机扣取 等都可以用到测试阶段 以随机扣取为例,对某张测试图像可得到 n 张随机扣取图像, 测试阶段只需用训练好的深度网络模型对 n 张图分别做预测,之后将预测 的各类置信度平均作为该测试图像最终预测结...

CodenameNC的博客 5410

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

CNN笔记(2)--网络参数初始化

7网络参数初始化 7.1 全零初始化 网络收敛到稳定状态时,参数(权值)在理想情况下应基本保持正负各半,期望为0 全0初始化可以使初始化全零时参数期望为0 但是,全0初始化不能训练 7.2随机初始化 仍然希望参数期望接近1 随机参数服从高斯分布或均匀分布进行初始化 7.2.1.高斯分布 高斯分布为均值为0,方差为1 的标准高斯分布 w = 0.001 .* ra...

CodenameNC的博客 4780

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

CNN笔记(1)---数据扩充与数据预处理

1.Data Augmentation 1.1 简单的数据扩充 图像水平翻转 随机扣取 尺度变换和旋转 色彩抖动:在RGB颜色空间对原有RGB色彩分布进行轻微扰动 也可以在HSV空间随机改变图像原有的饱和度和明度 (改变S和V通道的值) 或对色调进行微调(小范围改变H的值) 1.2 特殊的数据扩充方式 1.2.1 F...

CodenameNC的博客 2487

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

CNN笔记(4)--目标函数

9.目标函数(损失函数,代价函数) 9.1分类任务的目标函数 9.1.1 交叉熵损失函数(cross entropy)(SoftMax) Lcross&nbsp;entropy&nbsp;loss=Lsoftmax_loss=−1N∑i=1Nlogehyi∑Cj=1ehjLcross&nbsp;entropy&nbsp;loss=Lsoftmax_loss=−1N∑i=1Nlog⁡e...

CodenameNC的博客 1895

CNN笔记(3)---激活函数

8.Activation Function 8.1 Sigmoid 型函数 σ(x)=11+e(−x)σ(x)=11+e(−x) \sigma(x)=\frac{1}{1+e^{(-x)}} sigmoid 将输出响应的值域压缩到[0,1]之间 但是,两端大于5,小于-5的区域,梯度接近0,带来梯度的“饱和效应” 反向传播中无法传递误差 而且sigmoid 的值域均值并非为0,而...

CodenameNC的博客 1748

C++ 短路求值特性的利用

题目 求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。 解决方案 class Solution { public: int Sum_Solution(int n) { int res = n; res &amp;&amp; (res = res + Sum_S...

CodenameNC的博客 1074

Python Algorithms Learning Notes(1)--Asymptotic Notations

Lately , I've been reading《Python Algorithms》by Magnus Lie Hetland. To understand the contents better , I’ll keep notes about it through the whole process.

CodenameNC的博客 533

AI全栈实战 | 3.9-01 爬虫入门:requests 加 BeautifulSoup 三分钟跑通,但 90% 的人栽在这 4 个“礼貌“问题上

⚠️:本文内容仅用于。请遵守目标站点的服务条款与相关法律法规,不得对目标服务造成负担,不得采集、传播个人隐私数据。技术是中性的,边界在你手里。爬虫的入门技术(requests 发请求 + BeautifulSoup 解析)三分钟就能学会。真正区分"会用爬虫"和"会做爬虫的人"的,是这篇我们跑通"请求→解析→存储"的最小闭环,然后重点把"合规与礼貌"这根弦给你绷上。

源码获取 | 运行部署 | 定制二开修改,如果回复不及时请耐心等待,请见谅。 423

从一段视频到可漫游的 4D 有声场景:思路拆解与最小复现手记

只需一段手机视频,你就能生成可"走进去"的 4D 有声场景:转头时狗叫声方向随之变化,走近时声音更清晰。本文拆解 Video-to-4DAVScene 的核心思路,手把手带你用几十行 Python 搭出最小管线,把视频中的运动物体变成带空间位置的声源,并附上三个真实踩坑的排障经验,代码可直接跑。🎧

helloagent的博客 239

【每天一个 Python 小案例30】Python 基础知识综合小项目:我的工具盒

作为系列收官,本篇把前 29 篇的知识点合成一个能直接用的命令行工具"我的工具盒":计算器(用 ast 解析表达式,不碰 eval)、单位换算与温度转换(一张换算表 + 特例分支)、记账与分类统计(Decimal + JSON 持久化)、以及用"字典当命令表"把菜单和业务逻辑解耦的主循环。文中对比了 eval 的安全隐患与 ast 白名单的做法,解释了 lambda 闭包在字典里的写法与晚绑定陷阱,并在最后给出整个系列的知识地图,把变量、数据结构、控制流、函数、类、异常、文件、标准库八块内容对应到具体篇目。

xinjiyaya的博客 427

10分钟完成第一个Python小游戏

第一个项目不用找复杂的,‌直接选「猜数字小游戏」对应的教程‌就好——几乎所有入门教程都会讲这个项目,资料最多、遇到问题随便搜就能找到解决方法,不会卡壳,30分钟肯定能做完,非常容易建立信心。‌教程链接‌:直接搜标题👉 ‌《Python零基础入门项目:30分钟写完猜数字游戏》‌(优先选黑马程序员、鱼C-小甲鱼这两个UP主的版本,播放量都是百万级,口碑稳定)‌教程地址‌:打开菜鸟教程官网→找到「Python 实例」板块,直接在线写代码运行。全程不跳步,30分钟就能做完,做完能直接运行玩,成就感拉满。

mF44Job8l的博客 66

二进制木马免杀-Python 分离免杀与 Web 挂马

二进制木马免杀-Python 分离免杀与 Web 挂马

2503_94637398的博客 269
上一篇: Python Algorithms Learning Notes(1)--Asymptotic Notations
下一篇: Python 2.x 与 3.x 版本不同造成的报错处理
Codename-NC
博客等级 码龄12年 38粉丝 30原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值