Python 经典贪心算法之Prim算法案例详解

yizhihongxing

Sure, I'd be happy to help! Here is a detailed guide on the Prim algorithm in Python, including two examples:

Introduction to Prim Algorithm

Prim's algorithm is a greedy algorithm that finds a minimum spanning tree for a weighted undirected graph. The algorithm starts with a single vertex and gradually expands the tree by adding the cheapest edge that connects the tree to a new vertex. The algorithm continues until all vertices are included in the tree.

Prim Algorithm Implementation

Here is a Python implementation of the Prim algorithm:

import heapq

def prim(graph, start):
    visited = set()
    edges = [(0, start)]
    while edges:
        weight, vertex = heapq.heappop(edges)
        if vertex not in visited:
            visited.add(vertex)
            yield weight, vertex
            for neighbor, w in graph[vertex]:
                if neighbor not in visited:
                    heapq.heappush(edges, (w, neighbor))

The prim function takes a graph represented as a dictionary of lists, where each key is a vertex and the corresponding value is a list of tuples representing the edges and their weights. The start parameter specifies the starting vertex for the algorithm.

The function uses a heap to keep track of the cheapest edges that connect the tree to new vertices. The visited set keeps track of the vertices that have already been added to the tree.

The function yields the weight and vertex of each edge that is added to the tree.

Example 1: Finding the Minimum Spanning Tree

Let's use the prim function to find the minimum spanning tree of the following graph:

     2
  A-----B
  |\   /|
  | \ / |
3 |  X  | 1
  | / \ |
  |/   \|
  C-----D
     4

We can represent this graph as a dictionary of lists:

graph = {
    'A': [('B', 2), ('C', 3)],
    'B': [('A', 2), ('C', 1), ('D', 4)],
    'C': [('A', 3), ('B', 1), ('D', 5)],
    'D': [('B', 4), ('C', 5)]
}

To find the minimum spanning tree, we can call the prim function with the starting vertex 'A':

for weight, vertex in prim(graph, 'A'):
    print(f'{vertex} - {weight}')

This will output:

A - 0
B - 2
C - 3
D - 4

This means that the minimum spanning tree consists of the edges (A, B), (B, C), and (B, D), with a total weight of 2 + 1 + 4 = 7.

Example 2: Finding the Shortest Path

We can also use the prim function to find the shortest path between two vertices in a graph. For example, let's find the shortest path between vertices 'A' and 'D' in the same graph:

for weight, vertex in prim(graph, 'A'):
    if vertex == 'D':
        print(f'Shortest path weight: {weight}')
        break

This will output:

Shortest path weight: 4

This means that the shortest path between 'A' and 'D' is the edge (B, D), with a weight of 4.

I hope this guide helps you understand the Prim algorithm in Python!

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python 经典贪心算法之Prim算法案例详解 - Python技术站

(0)
上一篇 2023年5月14日
下一篇 2023年5月14日

相关文章

  • Python中常用功能的实现代码分享

    Python是一种高级编程语言,具有简洁易读、开发速度快等特点,广泛应用于各领域。在Python的编程过程中,有许多常用的功能需要实现。以下是Python中常用功能的实现代码分享的完整攻略。 一、环境配置 在进行Python编程之前,需要进行环境配置。Python环境配置一般包括三个步骤:下载Python、安装Python和安装开发工具。 下载Python …

    python 2023年5月19日
    00
  • PyQt5 pyqt多线程操作入门

    PyQt5 是一组 Python 绑定 Qt 库的 Python 模块,支持开发界面程序。通过多线程操作可以提升程序的运行效率和用户体验。以下是一份关于 PyQt5 多线程操作入门的攻略。 环境搭建 在开发 PyQt5 多线程程序前,我们需要先准备好以下两个软件的安装: Python 3.x。可前往官网下载并安装。 PyQt5 模块。使用 pip 命令安装,…

    python 2023年5月19日
    00
  • 从 Python 连接到 Apache Drill

    【问题标题】:Connect to Apache drill from Python从 Python 连接到 Apache Drill 【发布时间】:2023-04-04 00:48:01 【问题描述】: 有谁知道如何从 python 建立到 Apache Drill 的连接? 通常,通过pyodbc库的连接是这样的: connection = pyodbc…

    Python开发 2023年4月8日
    00
  • python+appium自动化测试之如何控制App的启动和退出

    下面我来详细讲解一下“Python+Appium自动化测试之如何控制App的启动和退出”。 准备工作 在开始讲解之前,我们需要安装好以下软件: Python3 Appium Android SDK 测试App的APK安装包 安装完成后,我们需要在命令行中输入以下命令来检查版本是否正确: # 检查 Python3 版本 python3 -V # 检查 Appi…

    python 2023年6月5日
    00
  • python实例方法的使用注意及代码实例

    下面是关于Python实例方法的使用注意及代码实例的攻略。 什么是Python实例方法? Python实例方法是类中定义的一种方法类型。它与类方法和静态方法不同,实例方法是绑定到类的实例上的方法。因此,在调用实例方法时,需要使用类的实例对象。 实例方法的主要特点是可以访问类的实例对象的属性和方法,同时还可以通过self参数引用实例对象本身。 下面是一个例子,…

    python 2023年5月31日
    00
  • Django打印出在数据库中执行的语句问题

    一、简介 Django提供了一个非常好用的ORM,可以方便的操作数据库,但是有时候我们需要查看ORM生成的SQL语句,以便优化ORM的使用。本攻略将详细介绍如何在Django中打印执行的SQL语句。 二、打印SQL语句的方法 在Django中,打印出在数据库中执行的SQL语句非常简单,我们只需要在settings.py中设置DEBUG=True,然后在执行O…

    python 2023年5月13日
    00
  • Python logging模块写入中文出现乱码

    如果在Python中使用logging模块写入中文时出现了乱码,可以按照以下步骤解决: 设置编码 在Python文件中加入以下代码: import logging import codecs import sys # 设置编码为utf-8 sys.stdout = codecs.getwriter("utf-8")(sys.stdout.…

    python 2023年5月20日
    00
  • 我用Python给班主任写了一个自动阅卷脚本(附源码)

    我用Python给班主任写了一个自动阅卷脚本(附源码) 背景 在学校中,老师经常需要阅卷,这是一个重复的枯燥无味的工作,同时也容易出错。为了解放老师的时间,提高学生作业批改效率,我使用Python编写了一个自动阅卷脚本。 思路 脚本的基本思路如下: 读取作业答案; 读取学生作业; 对每一份学生作业进行自动批改; 计算总分和各类题目的得分; 将批改结果保存到文…

    python 2023年5月19日
    00
合作推广
合作推广
分享本页
返回顶部