基本线性数据结构的Python实现

本文涉及的产品
实时计算 Flink 版,5000CU*H 3个月
简介: 基本线性数据结构的Python实现

数组
数组的设计
数组设计之初是在形式上依赖内存分配而成的,所以必须在使用前预先请求空间。这使得数组有以下特性:

请求空间以后大小固定,不能再改变(数据溢出问题);
在内存中有空间连续性的表现,中间不会存在其他程序需要调用的数据,为此数组的专用内存空间;
在旧式编程语言中(如有中阶语言之称的C),程序不会对数组的操作做下界判断,也就有潜在的越界操作的风险(比如会把数据写在运行中程序需要调用的核心部分的内存上)。
因为简单数组强烈倚赖电脑硬件之内存,所以不适用于现代的程序设计。欲使用可变大小、硬件无关性的数据类型,Java等程序设计语言均提供了更高级的数据结构:ArrayList、Vector等动态数组。

Python的数组
从严格意义上来说:Python里没有严格意义上的数组。
List可以说是Python里的数组,下面这段代码是CPython的实现List的结构体:

typedef struct {
PyObject_VAR_HEAD
/ Vector of pointers to list elements. list[0] is ob_item[0], etc. /
PyObject **ob_item;

/* ob_item contains space for 'allocated' elements.  The number
 * currently in use is ob_size.
 * Invariants:
 *     0 <= ob_size <= allocated
 *     len(list) == ob_size
 *     ob_item == NULL implies ob_size == allocated == 0
 * list.sort() temporarily sets allocated to -1 to detect mutations.
 *
 * Items must normally not be NULL, except during construction when
 * the list is not yet visible outside the function that builds it.
 */
Py_ssize_t allocated;

} PyListObject;

当然,在Python里它就是数组。
后面的一些结构也将用List来实现。

堆栈
什么是堆栈
堆栈(英语:stack),也可直接称栈,在计算机科学中,是一种特殊的串列形式的数据结构,它的特殊之处在于只能允许在链接串列或阵列的一端(称为堆叠顶端指标,英语:top)进行加入资料(英语:push)和输出资料(英语:pop)的运算。另外堆叠也可以用一维阵列或连结串列的形式来完成。堆叠的另外一个相对的操作方式称为伫列。

由于堆叠数据结构只允许在一端进行操作,因而按照后进先出(LIFO, Last In First Out)的原理运作。

特点
先入后出,后入先出。
除头尾节点之外,每个元素有一个前驱,一个后继。
操作
从原理可知,对堆栈(栈)可以进行的操作有:

top():获取堆栈顶端对象
push():向栈里添加一个对象
pop():从栈里推出一个对象
实现
class my_stack(object):
def init(self, value):
self.value = value

    # 前驱
    self.before = None
    # 后继
    self.behind = None

def __str__(self):
    return str(self.value)

def top(stack):
if isinstance(stack, my_stack):
if stack.behind is not None:
return top(stack.behind)
else:
return stack

def push(stack, ele):
push_ele = my_stack(ele)
if isinstance(stack, my_stack):
stack_top = top(stack)
push_ele.before = stack_top
push_ele.before.behind = push_ele
else:
raise Exception('不要乱扔东西进来好么')

def pop(stack):
if isinstance(stack, my_stack):
stack_top = top(stack)
if stack_top.before is not None:
stack_top.before.behind = None
stack_top.behind = None
return stack_top
else:
print('已经是栈顶了')

队列
什么是队列

和堆栈类似,唯一的区别是队列只能在队头进行出队操作,所以队列是是先进先出(FIFO, First-In-First-Out)的线性表

特点
先入先出,后入后出
除尾节点外,每个节点有一个后继
(可选)除头节点外,每个节点有一个前驱
操作
push():入队
pop():出队
实现
普通队列

class MyQueue():
def init(self, value=None):
self.value = value

    # 前驱
    # self.before = None
    # 后继
    self.behind = None

def __str__(self):
    if self.value is not None:
        return str(self.value)
    else:
        return 'None'

def create_queue():
"""仅有队头"""
return MyQueue()

def last(queue):
if isinstance(queue, MyQueue):
if queue.behind is not None:
return last(queue.behind)
else:
return queue

def push(queue, ele):
if isinstance(queue, MyQueue):
last_queue = last(queue)
new_queue = MyQueue(ele)
last_queue.behind = new_queue

def pop(queue):
if queue.behind is not None:
get_queue = queue.behind
queue.behind = queue.behind.behind
return get_queue
else:
print('队列里已经没有元素了')

def print_queue(queue):
print(queue)
if queue.behind is not None:
print_queue(queue.behind)

链表
什么是链表
链表(Linked list)是一种常见的基础数据结构,是一种线性表,但是并不会按线性的顺序存储数据,而是在每一个节点里存到下一个节点的指针(Pointer)。由于不必须按顺序存储,链表在插入的时候可以达到O(1)的复杂度,比另一种线性表顺序表快得多,但是查找一个节点或者访问特定编号的节点则需要O(n)的时间,而顺序表相应的时间复杂度分别是O(logn)和O(1)。

特点
使用链表结构可以克服数组链表需要预先知道数据大小的缺点,链表结构可以充分利用计算机内存空间,实现灵活的内存动态管理。但是链表失去了数组随机读取的优点,同时链表由于增加了结点的指针域,空间开销比较大。

操作
init():初始化
insert(): 插入
trave(): 遍历
delete(): 删除
find(): 查找
实现
此处仅实现双向列表

class LinkedList():
def init(self, value=None):
self.value = value

    # 前驱
    self.before = None
    # 后继
    self.behind = None

def __str__(self):
    if self.value is not None:
        return str(self.value)
    else:
        return 'None'

def init():
return LinkedList('HEAD')

def delete(linked_list):
if isinstance(linked_list, LinkedList):
if linked_list.behind is not None:
delete(linked_list.behind)
linked_list.behind = None
linked_list.before = None
linked_list.value = None

def insert(linked_list, index, node):
node = LinkedList(node)
if isinstance(linked_list, LinkedList):
i = 0
while linked_list.behind is not None:
if i == index:
break
i += 1
linked_list = linked_list.behind
if linked_list.behind is not None:
node.behind = linked_list.behind
linked_list.behind.before = node
node.before, linked_list.behind = linked_list, node

def remove(linked_list, index):
if isinstance(linked_list, LinkedList):
i = 0
while linked_list.behind is not None:
if i == index:
break
i += 1
linked_list = linked_list.behind
if linked_list.behind is not None:
linked_list.behind.before = linked_list.before
if linked_list.before is not None:
linked_list.before.behind = linked_list.behind
linked_list.behind = None
linked_list.before = None
linked_list.value = None

def trave(linked_list):
if isinstance(linked_list, LinkedList):
print(linked_list)
if linked_list.behind is not None:
trave(linked_list.behind)

def find(linked_list, index):
if isinstance(linked_list, LinkedList):
i = 0
while linked_list.behind is not None:
if i == index:
return linked_list
i += 1
linked_list = linked_list.behind
else:
if i < index:
raise Exception(404)
return linked_list

以上所有源代码均在GitHub共享,欢迎评论区留言,希望与大家共同进步!

相关实践学习
基于Hologres轻松玩转一站式实时仓库
本场景介绍如何利用阿里云MaxCompute、实时计算Flink和交互式分析服务Hologres开发离线、实时数据融合分析的数据大屏应用。
Linux入门到精通
本套课程是从入门开始的Linux学习课程,适合初学者阅读。由浅入深案例丰富,通俗易懂。主要涉及基础的系统操作以及工作中常用的各种服务软件的应用、部署和优化。即使是零基础的学员,只要能够坚持把所有章节都学完,也一定会受益匪浅。
目录
相关文章
|
7天前
|
算法 安全 大数据
揭秘!Python堆与优先队列:数据结构的秘密武器,让你的代码秒变高效战士!
【7月更文挑战第8天】Python的heapq模块和queue.PriorityQueue提供堆与优先队列功能,助你提升算法效率。堆用于快速找大数据集的第K大元素,如示例所示,时间复杂度O(n log k)。PriorityQueue在多线程中智能调度任务,如模拟下载管理器,按优先级处理任务。掌握这些工具,让代码运行更高效!
21 1
|
3天前
|
算法 Python
逆袭之路!用 Python 玩转图的 DFS 与 BFS,让数据结构难题无处遁形
【7月更文挑战第12天】图的遍历利器:DFS 和 BFS。Python 中,图可表示为邻接表或矩阵。DFS 沿路径深入,回溯时遍历所有可达顶点,适合找路径和环。BFS 层次遍历,先近后远,解决最短路径问题。两者在迷宫、网络路由等场景各显神通。通过练习,掌握这些算法,图处理将游刃有余。
10 3
|
2天前
|
存储 算法 Python
“解锁Python高级数据结构新姿势:图的表示与遍历,让你的算法思维跃升新高度
【7月更文挑战第13天】Python中的图数据结构用于表示复杂关系,通过节点和边连接。常见的表示方法是邻接矩阵(适合稠密图)和邻接表(适合稀疏图)。图遍历包括DFS(深度优先搜索)和BFS(广度优先搜索):DFS深入探索分支,BFS逐层访问邻居。掌握这些技巧对优化算法和解决实际问题至关重要。**
9 1
|
3天前
|
存储 缓存 Python
Python中的列表(List)和元组(Tuple)是两种重要的数据结构
【7月更文挑战第12天】Python中的列表(List)和元组(Tuple)是两种重要的数据结构
6 1
|
5天前
|
存储 算法 调度
惊呆了!Python高级数据结构堆与优先队列,竟然能这样优化你的程序性能!
【7月更文挑战第10天】Python的heapq模块实现了堆和优先队列,提供heappush和heappop等函数,支持O(log n)时间复杂度的操作。优先队列常用于任务调度和图算法,优化性能。例如,Dijkstra算法利用最小堆加速路径查找。堆通过列表存储,内存效率高。示例展示了添加、弹出和自定义优先级元素。使用堆优化程序,提升效率。
15 2
|
5天前
|
机器学习/深度学习 数据采集 数据可视化
Python实现支持向量机SVM分类模型线性SVM决策过程的可视化项目实战
Python实现支持向量机SVM分类模型线性SVM决策过程的可视化项目实战
Python实现支持向量机SVM分类模型线性SVM决策过程的可视化项目实战
|
19天前
|
存储 Python
Python中使用列表和字典来存储和处理复杂的数据结构
Python中使用列表和字典来存储和处理复杂的数据结构
|
1天前
|
存储 数据可视化 数据处理
`geopandas`是一个开源项目,它为Python提供了地理空间数据处理的能力。它基于`pandas`库,并扩展了其对地理空间数据(如点、线、多边形等)的支持。`GeoDataFrame`是`geopandas`中的核心数据结构,它类似于`pandas`的`DataFrame`,但包含了一个额外的地理列(通常是`geometry`列),用于存储地理空间数据。
`geopandas`是一个开源项目,它为Python提供了地理空间数据处理的能力。它基于`pandas`库,并扩展了其对地理空间数据(如点、线、多边形等)的支持。`GeoDataFrame`是`geopandas`中的核心数据结构,它类似于`pandas`的`DataFrame`,但包含了一个额外的地理列(通常是`geometry`列),用于存储地理空间数据。
4 0
|
7天前
|
算法 安全 调度
逆天改命!Python高级数据结构堆(Heap)与优先队列,让你的算法效率飙升至宇宙级!
【7月更文挑战第8天】Python的heapq模块和queue.PriorityQueue实现了堆和优先队列,提供高效算法解决方案。堆用于Dijkstra算法求解最短路径,例如在图论问题中;PriorityQueue则在多线程下载管理中确保高优先级任务优先执行。这两个数据结构提升效率,简化代码,是编程中的强大工具。
10 0
|
7天前
|
安全 调度 Python
Python堆与优先队列:不只是数据结构,更是你编程路上的超级加速器!
【7月更文挑战第8天】Python的heapq模块和queue.PriorityQueue提供堆与优先队列功能。堆,作为完全二叉树,支持排序性质,heapq用于单线程操作;PriorityQueue在多线程中保证安全。通过示例展示了如何插入、删除任务,以及在多线程任务调度中的应用。堆与优先队列是高效编程的关键工具,提升代码性能与并发处理能力。
9 0