This document summarizes a lecture on graph-theoretic models and algorithms for finding shortest paths in graphs. It introduces graphs and their representations as nodes connected by edges. It presents Python classes for representing graphs and shows implementations of depth-first search (DFS) and breadth-first search (BFS) algorithms to find the shortest path between two nodes in a graph. Examples are provided to demonstrate how DFS and BFS can find shortest paths in a graph modeling connected cities.
An accademic project developed for the Web Information Retrieval class at Sapienza Università di Roma, Master Degree in Computer Engineering A.Y. 2019-20
The goal of the project is to rank computer scientists based on their influence using Google's PageRank and HITS algorithm.
For further information you can check our repository:
https://github.com/LucaTomei/Computer_Scientists
Members of the project:
Luca Tomei
Andrea Aurizi
Daniele Iacomini
Code is not text! How graph technologies can help us to understand our code b...Andreas Dewes
Today, we almost exclusively think of code in software projects as a collection of text files. The tools that we use (version control systems, IDEs, code analyzers) also use text as the primary storage format for code. In fact, the belief that “code is text” is so deeply ingrained in our heads that we never question its validity or even become aware of the fact that there are other ways to look at code.
In my talk I will explain why treating code as text is a very bad idea which actively holds back our understanding and creates a range of problems in large software projects. I will then show how we can overcome (some of) these problems by treating and storing code as data, and more specifically as a graph. I will show specific examples of how we can use this approach to improve our understanding of large code bases, increase code quality and automate certain aspects of software development.
Finally, I will outline my personal vision of the future of programming, which is a future where we no longer primarily interact with code bases using simple text editors. I will also give some ideas on how we might get to that future.
The document summarizes a lecture on further details of the graphics pipeline. It discusses how triangles described by vertex positions in normalized device coordinates are rasterized into pixels on the screen. The lecture covers oriented edge equations, being inside a triangle, rasterization approaches like scanline rasterization, and basic fragment shading through color interpolation. Homework status and the lecturer's office hours are also provided.
GraphFrames: Graph Queries in Spark SQL by Ankur DaveSpark Summit
GraphFrames provides a unified API for graph queries and algorithms in Spark SQL. It translates graph patterns and algorithms to relational operations optimized by the Spark SQL query optimizer. Materializing the right views, such as the triplet view for GraphX algorithms or user-defined views for queries, can improve performance. An evaluation shows GraphFrames outperforms Neo4j for unanchored queries and approaches GraphX performance for graph algorithms using Spark SQL. Future work includes automatically suggesting optimal views and exploiting attribute-based partitioning.
This document discusses network representation and analysis. It defines networks as consisting of nodes (vertices) and edges, and describes different ways to represent networks mathematically using adjacency matrices, incidence matrices, and Laplacian matrices. It also discusses visualizing networks using multidimensional scaling and plotting them in R. Special types of networks like complete graphs and random graphs are briefly introduced.
These are slides from our Big Data Warehouse Meetup in April. We talked about NoSQL databases: What they are, how they’re used and where they fit in existing enterprise data ecosystems.
Mike O’Brian from 10gen, introduced the syntax and usage patterns for a new aggregation system in MongoDB and give some demonstrations of aggregation using the new system. The new MongoDB aggregation framework makes it simple to do tasks such as counting, averaging, and finding minima or maxima while grouping by keys in a collection, complementing MongoDB’s built-in map/reduce capabilities.
For more information, visit our website at http://casertaconcepts.com/ or email us at info@casertaconcepts.com.
An accademic project developed for the Web Information Retrieval class at Sapienza Università di Roma, Master Degree in Computer Engineering A.Y. 2019-20
The goal of the project is to rank computer scientists based on their influence using Google's PageRank and HITS algorithm.
For further information you can check our repository:
https://github.com/LucaTomei/Computer_Scientists
Members of the project:
Luca Tomei
Andrea Aurizi
Daniele Iacomini
Code is not text! How graph technologies can help us to understand our code b...Andreas Dewes
Today, we almost exclusively think of code in software projects as a collection of text files. The tools that we use (version control systems, IDEs, code analyzers) also use text as the primary storage format for code. In fact, the belief that “code is text” is so deeply ingrained in our heads that we never question its validity or even become aware of the fact that there are other ways to look at code.
In my talk I will explain why treating code as text is a very bad idea which actively holds back our understanding and creates a range of problems in large software projects. I will then show how we can overcome (some of) these problems by treating and storing code as data, and more specifically as a graph. I will show specific examples of how we can use this approach to improve our understanding of large code bases, increase code quality and automate certain aspects of software development.
Finally, I will outline my personal vision of the future of programming, which is a future where we no longer primarily interact with code bases using simple text editors. I will also give some ideas on how we might get to that future.
The document summarizes a lecture on further details of the graphics pipeline. It discusses how triangles described by vertex positions in normalized device coordinates are rasterized into pixels on the screen. The lecture covers oriented edge equations, being inside a triangle, rasterization approaches like scanline rasterization, and basic fragment shading through color interpolation. Homework status and the lecturer's office hours are also provided.
GraphFrames: Graph Queries in Spark SQL by Ankur DaveSpark Summit
GraphFrames provides a unified API for graph queries and algorithms in Spark SQL. It translates graph patterns and algorithms to relational operations optimized by the Spark SQL query optimizer. Materializing the right views, such as the triplet view for GraphX algorithms or user-defined views for queries, can improve performance. An evaluation shows GraphFrames outperforms Neo4j for unanchored queries and approaches GraphX performance for graph algorithms using Spark SQL. Future work includes automatically suggesting optimal views and exploiting attribute-based partitioning.
This document discusses network representation and analysis. It defines networks as consisting of nodes (vertices) and edges, and describes different ways to represent networks mathematically using adjacency matrices, incidence matrices, and Laplacian matrices. It also discusses visualizing networks using multidimensional scaling and plotting them in R. Special types of networks like complete graphs and random graphs are briefly introduced.
These are slides from our Big Data Warehouse Meetup in April. We talked about NoSQL databases: What they are, how they’re used and where they fit in existing enterprise data ecosystems.
Mike O’Brian from 10gen, introduced the syntax and usage patterns for a new aggregation system in MongoDB and give some demonstrations of aggregation using the new system. The new MongoDB aggregation framework makes it simple to do tasks such as counting, averaging, and finding minima or maxima while grouping by keys in a collection, complementing MongoDB’s built-in map/reduce capabilities.
For more information, visit our website at http://casertaconcepts.com/ or email us at info@casertaconcepts.com.
I'll found many papers and books talking about category theory, but many peoples still don't know how it can help. On this talk I'll help you better understand how math can help us develop a software more composable.
Coder on Beer - Concrete
2018 - São Paulo
The document proposes a K-Main Routes (KMR) algorithm to summarize spatial network activity. KMR finds a set of k routes that maximize activity coverage on a network. It introduces design decisions like inactive node pruning, Network Voronoi activity assignment, and divide-and-conquer summary path recomputation to improve runtime. The algorithm is evaluated analytically, experimentally on synthetic and real data, and through a case study comparing to geometry-based methods. KMR summarizes network activity for applications like crime analysis and environmental modeling.
PostgreSQL: Advanced features in practiceJano Suchal
The document discusses several advanced features of PostgreSQL including:
1) Transactional DDL which allows DDL statements to be executed transactionally.
2) Cost-based query optimization and graphical EXPLAIN plans which help choose the most efficient query plan.
3) Features like partial indexes, function indexes, k-nearest search, views, and window functions which provide powerful ways to query and analyze data.
Slides from our PacificVis 2015 presentation.
The paper tackles the problems of the “giant hairballs”, the dense and tangled structures often resulting from visualiza- tion of large social graphs. Proposed is a high-dimensional rotation technique called AGI3D, combined with an ability to filter elements based on social centrality values. AGI3D is targeted for a high-dimensional embedding of a social graph and its projection onto 3D space. It allows the user to ro- tate the social graph layout in the high-dimensional space by mouse dragging of a vertex. Its high-dimensional rotation effects give the user an illusion that he/she is destructively reshaping the social graph layout but in reality, it assists the user to find a preferred positioning and direction in the high- dimensional space to look at the internal structure of the social graph layout, keeping it unmodified. A prototype im- plementation of the proposal called Social Viewpoint Finder is tested with about 70 social graphs and this paper reports four of the analysis results.
GSP 125 RANK Education for Service--gsp125rank.comclaric25
The document provides a guide for a GSP 125 final exam with multiple choice questions covering topics in C++ classes, objects, inheritance, templates, pointers, and more. It also includes coding questions to test understanding of concepts like writing classes, using inheritance, dynamically allocating memory, and more. The guide provides the questions, points possible for each, and blank space for answers. It directs students to a website for more exam preparation materials.
GraphFrames: Graph Queries In Spark SQLSpark Summit
GraphFrames provides a unified API for graph queries and algorithms in Apache Spark SQL. It translates graph patterns and algorithms to relational operations optimized by the Spark SQL query optimizer. Materialized views can greatly improve performance of graph queries by enabling efficient join elimination and reordering. An evaluation found GraphFrames outperforms Neo4j for unanchored queries and approaches performance of GraphX for graph algorithms using whole-stage code generation in Spark SQL. Future work includes automatically suggesting optimal views and exploiting data partitioning.
GraphX: Graph Analytics in Apache Spark (AMPCamp 5, 2014-11-20)Ankur Dave
GraphX is a graph processing framework built into Apache Spark. This talk introduces GraphX, describes key features of its API, and gives an update on its status.
For more course tutorials visit
www.newtonhelp.com
Question 1. 1. In addition to grouping functions together, a class also groups (Points : 3)
libraries.
math operations.
print statements.
For more course tutorials visit
www.newtonhelp.com
Question 1. 1. In addition to grouping functions together, a class also groups (Points : 3)
libraries.
math operations.
GSP 125 Become Exceptional/newtonhelp.combellflower148
For more course tutorials visit
www.newtonhelp.com
Question 1. 1. In addition to grouping functions together, a class also groups (Points : 3)
libraries.
math operations.
print statements.
variables.
For more course tutorials visit
www.newtonhelp.com
Question 1. 1. In addition to grouping functions together, a class also groups (Points : 3)
libraries.
math operations.
print statements.
variables.
I am Andrew O. I am a Computer Science Assignment Help Expert at programminghomeworkhelp.com. I hold a Ph.D. in Programming, Southampton, UK. I have been helping students with their homework for the past 10 years. I solve assignments related to Computer Science.
Visit programminghomeworkhelp.com or email support@programminghomeworkhelp.com.You can also call on +1 678 648 4277 for any assistance with Computer Science assignments.
This document provides code for a simple text-based game that uses object-oriented principles in C++. The game code is provided to demonstrate refactoring a procedural program into an object-oriented structure. Students are instructed to refactor the given code by:
1) Creating classes and structures to represent game entities and vectors
2) Adding game logic to check for a win or loss condition
3) Using an enum to represent different game states
The refactored code is intended to demonstrate OOP concepts like encapsulation, abstraction, and polymorphism.
For more course tutorials visit
www.tutorialrank.com
Question 1. 1. In addition to grouping functions together, a class also groups (Points : 3)
libraries.
math operations.
print statements.
variables.
Lokesh 's Ip project Pokemon informationbholu803201
This document describes a library management system project created by a student for their Class XII examination. It includes a certificate signed by the student and teacher, an acknowledgement, index, and sections on project analysis, functions and modules, source code, outputs and tables, and bibliography. The project uses Python and MySQL to create a database with tables for books, book issues, and returns to allow a library to track its inventory and lending activities.
This presentation has been prepared by Oleksii Prohonnyi for LvivJS 2015 conference (http://lvivjs.org.ua/)
See the speech in Russian by the following link: https://youtu.be/oi7JhB8eWnA
The document discusses domain-driven design (DDD) and how it was applied to a solar system simulation case study using C# 3.0 features. It describes modeling the problem domain, including defining a universe class with methods to calculate gravitational forces and move bodies. It also covers wrapping the domain model with other layers like the user interface, data access, and bootstrap code. C# 3.0 features like lambda expressions, LINQ, and extension methods were used to implement domain logic and interfaces to the domain from other layers.
For more classes visit
www.snaptutorial.com
Question 1. 1. In addition to grouping functions together, a class also groups (Points : 3)
libraries.
math operations.
print statements.
variables.
Question 2. 2. Hiding data in a class is also called (Points : 3)
Question 1. 1. In addition to grouping functions together, a class also groups (Points : 3)
libraries.
math operations.
print statements.
variables.
Question 2. 2. Hiding data in a class is also called (Points : 3)
encapsulation.
accessibility inversion.
confusion culling.
redirection.
Gsp 125 Enthusiastic Study / snaptutorial.comStephenson101
Question 1. 1. In addition to grouping functions together, a class also groups (Points : 3)
libraries.
math operations.
print statements.
variables.
Question 2. 2. Hiding data in a class is also called (Points : 3)
encapsulation.
accessibility inversion.
confusion culling.
redirection.
Open Source Contributions to Postgres: The Basics POSETTE 2024ElizabethGarrettChri
Postgres is the most advanced open-source database in the world and it's supported by a community, not a single company. So how does this work? How does code actually get into Postgres? I recently had a patch submitted and committed and I want to share what I learned in that process. I’ll give you an overview of Postgres versions and how the underlying project codebase functions. I’ll also show you the process for submitting a patch and getting that tested and committed.
I'll found many papers and books talking about category theory, but many peoples still don't know how it can help. On this talk I'll help you better understand how math can help us develop a software more composable.
Coder on Beer - Concrete
2018 - São Paulo
The document proposes a K-Main Routes (KMR) algorithm to summarize spatial network activity. KMR finds a set of k routes that maximize activity coverage on a network. It introduces design decisions like inactive node pruning, Network Voronoi activity assignment, and divide-and-conquer summary path recomputation to improve runtime. The algorithm is evaluated analytically, experimentally on synthetic and real data, and through a case study comparing to geometry-based methods. KMR summarizes network activity for applications like crime analysis and environmental modeling.
PostgreSQL: Advanced features in practiceJano Suchal
The document discusses several advanced features of PostgreSQL including:
1) Transactional DDL which allows DDL statements to be executed transactionally.
2) Cost-based query optimization and graphical EXPLAIN plans which help choose the most efficient query plan.
3) Features like partial indexes, function indexes, k-nearest search, views, and window functions which provide powerful ways to query and analyze data.
Slides from our PacificVis 2015 presentation.
The paper tackles the problems of the “giant hairballs”, the dense and tangled structures often resulting from visualiza- tion of large social graphs. Proposed is a high-dimensional rotation technique called AGI3D, combined with an ability to filter elements based on social centrality values. AGI3D is targeted for a high-dimensional embedding of a social graph and its projection onto 3D space. It allows the user to ro- tate the social graph layout in the high-dimensional space by mouse dragging of a vertex. Its high-dimensional rotation effects give the user an illusion that he/she is destructively reshaping the social graph layout but in reality, it assists the user to find a preferred positioning and direction in the high- dimensional space to look at the internal structure of the social graph layout, keeping it unmodified. A prototype im- plementation of the proposal called Social Viewpoint Finder is tested with about 70 social graphs and this paper reports four of the analysis results.
GSP 125 RANK Education for Service--gsp125rank.comclaric25
The document provides a guide for a GSP 125 final exam with multiple choice questions covering topics in C++ classes, objects, inheritance, templates, pointers, and more. It also includes coding questions to test understanding of concepts like writing classes, using inheritance, dynamically allocating memory, and more. The guide provides the questions, points possible for each, and blank space for answers. It directs students to a website for more exam preparation materials.
GraphFrames: Graph Queries In Spark SQLSpark Summit
GraphFrames provides a unified API for graph queries and algorithms in Apache Spark SQL. It translates graph patterns and algorithms to relational operations optimized by the Spark SQL query optimizer. Materialized views can greatly improve performance of graph queries by enabling efficient join elimination and reordering. An evaluation found GraphFrames outperforms Neo4j for unanchored queries and approaches performance of GraphX for graph algorithms using whole-stage code generation in Spark SQL. Future work includes automatically suggesting optimal views and exploiting data partitioning.
GraphX: Graph Analytics in Apache Spark (AMPCamp 5, 2014-11-20)Ankur Dave
GraphX is a graph processing framework built into Apache Spark. This talk introduces GraphX, describes key features of its API, and gives an update on its status.
For more course tutorials visit
www.newtonhelp.com
Question 1. 1. In addition to grouping functions together, a class also groups (Points : 3)
libraries.
math operations.
print statements.
For more course tutorials visit
www.newtonhelp.com
Question 1. 1. In addition to grouping functions together, a class also groups (Points : 3)
libraries.
math operations.
GSP 125 Become Exceptional/newtonhelp.combellflower148
For more course tutorials visit
www.newtonhelp.com
Question 1. 1. In addition to grouping functions together, a class also groups (Points : 3)
libraries.
math operations.
print statements.
variables.
For more course tutorials visit
www.newtonhelp.com
Question 1. 1. In addition to grouping functions together, a class also groups (Points : 3)
libraries.
math operations.
print statements.
variables.
I am Andrew O. I am a Computer Science Assignment Help Expert at programminghomeworkhelp.com. I hold a Ph.D. in Programming, Southampton, UK. I have been helping students with their homework for the past 10 years. I solve assignments related to Computer Science.
Visit programminghomeworkhelp.com or email support@programminghomeworkhelp.com.You can also call on +1 678 648 4277 for any assistance with Computer Science assignments.
This document provides code for a simple text-based game that uses object-oriented principles in C++. The game code is provided to demonstrate refactoring a procedural program into an object-oriented structure. Students are instructed to refactor the given code by:
1) Creating classes and structures to represent game entities and vectors
2) Adding game logic to check for a win or loss condition
3) Using an enum to represent different game states
The refactored code is intended to demonstrate OOP concepts like encapsulation, abstraction, and polymorphism.
For more course tutorials visit
www.tutorialrank.com
Question 1. 1. In addition to grouping functions together, a class also groups (Points : 3)
libraries.
math operations.
print statements.
variables.
Lokesh 's Ip project Pokemon informationbholu803201
This document describes a library management system project created by a student for their Class XII examination. It includes a certificate signed by the student and teacher, an acknowledgement, index, and sections on project analysis, functions and modules, source code, outputs and tables, and bibliography. The project uses Python and MySQL to create a database with tables for books, book issues, and returns to allow a library to track its inventory and lending activities.
This presentation has been prepared by Oleksii Prohonnyi for LvivJS 2015 conference (http://lvivjs.org.ua/)
See the speech in Russian by the following link: https://youtu.be/oi7JhB8eWnA
The document discusses domain-driven design (DDD) and how it was applied to a solar system simulation case study using C# 3.0 features. It describes modeling the problem domain, including defining a universe class with methods to calculate gravitational forces and move bodies. It also covers wrapping the domain model with other layers like the user interface, data access, and bootstrap code. C# 3.0 features like lambda expressions, LINQ, and extension methods were used to implement domain logic and interfaces to the domain from other layers.
For more classes visit
www.snaptutorial.com
Question 1. 1. In addition to grouping functions together, a class also groups (Points : 3)
libraries.
math operations.
print statements.
variables.
Question 2. 2. Hiding data in a class is also called (Points : 3)
Question 1. 1. In addition to grouping functions together, a class also groups (Points : 3)
libraries.
math operations.
print statements.
variables.
Question 2. 2. Hiding data in a class is also called (Points : 3)
encapsulation.
accessibility inversion.
confusion culling.
redirection.
Gsp 125 Enthusiastic Study / snaptutorial.comStephenson101
Question 1. 1. In addition to grouping functions together, a class also groups (Points : 3)
libraries.
math operations.
print statements.
variables.
Question 2. 2. Hiding data in a class is also called (Points : 3)
encapsulation.
accessibility inversion.
confusion culling.
redirection.
Open Source Contributions to Postgres: The Basics POSETTE 2024ElizabethGarrettChri
Postgres is the most advanced open-source database in the world and it's supported by a community, not a single company. So how does this work? How does code actually get into Postgres? I recently had a patch submitted and committed and I want to share what I learned in that process. I’ll give you an overview of Postgres versions and how the underlying project codebase functions. I’ll also show you the process for submitting a patch and getting that tested and committed.
Codeless Generative AI Pipelines
(GenAI with Milvus)
https://ml.dssconf.pl/user.html#!/lecture/DSSML24-041a/rate
Discover the potential of real-time streaming in the context of GenAI as we delve into the intricacies of Apache NiFi and its capabilities. Learn how this tool can significantly simplify the data engineering workflow for GenAI applications, allowing you to focus on the creative aspects rather than the technical complexities. I will guide you through practical examples and use cases, showing the impact of automation on prompt building. From data ingestion to transformation and delivery, witness how Apache NiFi streamlines the entire pipeline, ensuring a smooth and hassle-free experience.
Timothy Spann
https://www.youtube.com/@FLaNK-Stack
https://medium.com/@tspann
https://www.datainmotion.dev/
milvus, unstructured data, vector database, zilliz, cloud, vectors, python, deep learning, generative ai, genai, nifi, kafka, flink, streaming, iot, edge
The Ipsos - AI - Monitor 2024 Report.pdfSocial Samosa
According to Ipsos AI Monitor's 2024 report, 65% Indians said that products and services using AI have profoundly changed their daily life in the past 3-5 years.
Predictably Improve Your B2B Tech Company's Performance by Leveraging DataKiwi Creative
Harness the power of AI-backed reports, benchmarking and data analysis to predict trends and detect anomalies in your marketing efforts.
Peter Caputa, CEO at Databox, reveals how you can discover the strategies and tools to increase your growth rate (and margins!).
From metrics to track to data habits to pick up, enhance your reporting for powerful insights to improve your B2B tech company's marketing.
- - -
This is the webinar recording from the June 2024 HubSpot User Group (HUG) for B2B Technology USA.
Watch the video recording at https://youtu.be/5vjwGfPN9lw
Sign up for future HUG events at https://events.hubspot.com/b2b-technology-usa/
1. Graph-theoretic Models,
Lecture 3, Segment 1
John Guttag
MIT Department of Electrical Engineering and
Computer Science
6.00.2X LECTURE 3 1
2. Programs that help us understand the world and solve
practical problems
Saw how we could map the informal problem of
choosing what to eat into an optimization problem,
and how we could design a program to solve it
Now want to look at class of models called graphs
Computational Models
6.00.2X LECTURE 3 2
3. Set of nodes (vertices)
◦ Might have properties associated with them
Set of edges (arcs) each consisting of a pair of nodes
◦ Undirected (graph)
◦ Directed (digraph)
◦ Source (parent) and destination (child) nodes
◦ Unweighted or weighted
What’s a Graph?
6.00.2X LECTURE 3 3
4. Set of nodes (vertices)
◦ Might have properties associated with them
Set of edges (arcs) each consisting of a pair of nodes
◦ Undirected (graph)
◦ Directed (digraph)
◦ Source (parent) and destination (child) nodes
◦ Unweighted or weighted
What’s a Graph?
6.00.2X LECTURE 3 4
10
12
3
5. To capture useful relationships among entities
◦ Rail links between Paris and London
◦ How the atoms in a molecule related to one another
◦ Ancestral relationships
Why Graphs?
6.00.2X LECTURE 3 5
6. A directed graph in which each pair of nodes is
connected by a single path
◦ Recall the search trees we used to solve knapsack
problem
Trees: An Important Special Case
6.00.2X LECTURE 3 6
7. World is full of networks based on relationships
◦ Computer networks
◦ Transportation networks
◦ Financial networks
◦ Sewer networks
◦ Political networks
◦ Criminal networks
◦ Social networks
◦ Etc.
Why Graphs Are So Useful
6.00.2X LECTURE 3 7
mapr.com
9. Model road system using a digraph
◦ Nodes: points where roads end or meet
◦ Edges: connections between points
◦ Each edge has a weight indicating time it will take to get
from source node to destination node for that edge
Solve a graph optimization problem
◦ Shortest weighted path between my house and my office
Getting John to the Office
6.00.2X LECTURE 3 9
CC-BY SusanLesch
10. First Reported Use of Graph Theory
6.00.2X LECTURE 3 10
Bridges of
Königsberg
(1735)
Possible to take
a walk that
traverses each of
the 7 bridges
exactly once?
11. Leonhard Euler’s Model
6.00.2X LECTURE 3 11
Each island a node
Each bridge an undirected edge
Model abstracts away irrelevant details
◦ Size of islands
◦ Length of bridges
Is there a path that contains each edge exactly once?
13. Graph-theoretic Models,
Lecture 3, Segment 2
John Guttag
MIT Department of Electrical Engineering and
Computer Science
6.00.2X LECTURE 3 1
14. Class Node
6.00.2X LECTURE 3 2
class Node(object):
def __init__(self, name):
"""Assumes name is a string"""
self.name = name
def getName(self):
return self.name
def __str__(self):
return self.name
15. Class Edge
6.00.2X LECTURE 3 3
class Edge(object):
def __init__(self, src, dest):
"""Assumes src and dest are nodes"""
self.src = src
self.dest = dest
def getSource(self):
return self.src
def getDestination(self):
return self.dest
def __str__(self):
return self.src.getName() + '->’
+ self.dest.getName()
16. Adjacency matrix
◦ Rows: source nodes
◦ Columns: destination nodes
◦ Cell[s, d] = 1 if there is an edge from s to d
0 otherwise
Adjacency list
◦ Associate with each node a list of destination nodes
Common Representations of Digraphs
6.00.2X LECTURE 3 4
17. Class Digraph, part 1
6.00.2X LECTURE 3 5
class Digraph(object):
"""edges is a dict mapping each node to a list of
its children""”
def __init__(self):
self.edges = {}
def addNode(self, node):
if node in self.edges:
raise ValueError('Duplicate node')
else:
self.edges[node] = []
def addEdge(self, edge):
src = edge.getSource()
dest = edge.getDestination()
if not (src in self.edges and dest in self.edges):
raise ValueError('Node not in graph')
self.edges[src].append(dest)
18. Class Digraph, part 2
6.00.2X LECTURE 3 6
def childrenOf(self, node):
return self.edges[node]
def hasNode(self, node):
return node in self.edges
def getNode(self, name):
for n in self.edges:
if n.getName() == name:
return n
raise NameError(name)
def __str__(self):
result = ''
for src in self.edges:
for dest in self.edges[src]:
result = result + src.getName() + '->'
+ dest.getName() + 'n'
return result[:-1] #omit final newline
19. Why is Graph a subclass of digraph?
Remember the substitution rule from 6.00.1x?
◦ If client code works correctly using an instance of the
supertype, it should also work correctly when an instance
of the subtype is substituted for the instance of the
supertype
Any program that works with a Digraph will also work
with a Graph (but not vice versa)
Class Graph
6.00.2X LECTURE 3 7
class Graph(Digraph):
def addEdge(self, edge):
Digraph.addEdge(self, edge)
rev = Edge(edge.getDestination(), edge.getSource())
Digraph.addEdge(self, rev)
20. Shortest path from n1 to n2
◦ Shortest sequence of edges such that
◦ Source node of first edge is n1
◦ Destination of last edge is n2
◦ For edges, e1 and e2, in the sequence, if e2 follows e1 in the
sequence, the source of e2 is the destination of e1
Shortest weighted path
◦ Minimize the sum of the weights of the edges in the path
A Classic Graph Optimization Problem
6.00.2X LECTURE 3 8
21. Finding a route from one city to another
Designing communication networks
Finding a path for a molecule through a chemical
labyrinth
…
Some Shortest Path Problems
6.00.2X LECTURE 3 9
CC-BY Juliaytsai94
www.google.com
22. An Example
6.00.2X LECTURE 3 10
Boston
Providence New York
Chicago Denver
Phoenix
Los Angeles
Adjacency List
Boston: Providence, New York
Providence: Boston, New York
New York: Chicago
Chicago: Denver, Phoenix
Denver: Phoenix, New York
Los Angeles: Boston
25. Graph-theoretic Models,
Lecture 3, Segment 3
John Guttag
MIT Department of Electrical Engineering and
Computer Science
6.00.2X LECTURE 3 1
26. Algorithm 1, depth-first search (DFS)
Similar to left-first depth-first method of enumerating
a search tree (Lecture 2)
Main difference is that graph might have cycles, so we
must keep track of what nodes we have visited
Finding the Shortest Path
6.00.2X LECTURE 3 2
27. Depth First Search (DFS)
6.00.2X LECTURE 3 3
def DFS(graph, start, end, path, shortest):
path = path + [start]
if start == end:
return path
for node in graph.childrenOf(start):
if node not in path: #avoid cycles
if shortest == None or len(path) < len(shortest):
newPath = DFS(graph, node, end, path,
shortest, toPrint)
if newPath != None:
shortest = newPath
return shortest
def shortestPath(graph, start, end):
return DFS(graph, start, end, [], None, toPrint)
DFS called from a
wrapper function:
shortestPath
Gets recursion started properly
Provides appropriate abstraction
28. Test DFS
6.00.2X LECTURE 3 4
def testSP(source, destination):
g = buildGraph()
sp = shortestPath(g, g.getNode(source), g.getNode(destination)
if sp != None:
print('Shortest path from', source, 'to',
destination, 'is', printPath(sp))
else:
print('There is no path from', source, 'to', destination)
testSP('Boston', ’Chicago')
29. An Example
6.00.2X LECTURE 3 5
Boston
Providence New York
Chicago Denver
Phoenix
Los Angeles
Adjacency List
Boston: Providence, New York
Providence: Boston, New York
New York: Chicago
Chicago: Denver, Phoenix
Denver: Phoenix, New York
Los Angeles: Boston
30. Current DFS path: Chicago
Current DFS path: Chicago->Denver
Current DFS path: Chicago->Denver->Phoenix
Current DFS path: Chicago->Denver->New York
Already visited Chicago
There is no path from Chicago to Boston
Output (Chicago to Boston)
6.00.2X LECTURE 3 6
Boston
Providence New York
Chicago Denver
Phoenix
Los Angeles
31. Current DFS path: Boston
Current DFS path: Boston->Providence
Already visited Boston
Current DFS path: Boston->Providence->New York
Current DFS path: Boston->Providence->New York->Chicago
Current DFS path: Boston->Providence->New York->Chicago->Denver
Current DFS path: Boston->Providence->New York->Chicago->Denver->Phoenix Found path
Already visited New York
Current DFS path: Boston->New York
Current DFS path: Boston->New York->Chicago
Current DFS path: Boston->New York->Chicago->Denver
Current DFS path: Boston->New York->Chicago->Denver->Phoenix Found a shorter path
Already visited New York
Shortest path from Boston to Phoenix is Boston->New York->Chicago->Denver->Phoenix
Output (Boston to Phoenix)
6.00.2X LECTURE 3 7
32. Algorithm 2: Breadth-first Search (BFS)
6.00.2X LECTURE 3 8
def BFS(graph, start, end, toPrint = False):
initPath = [start]
pathQueue = [initPath]
if toPrint:
print('Current BFS path:', printPath(pathQueue))
while len(pathQueue) != 0:
#Get and remove oldest element in pathQueue
tmpPath = pathQueue.pop(0)
print('Current BFS path:', printPath(tmpPath))
lastNode = tmpPath[-1]
if lastNode == end:
return tmpPath
for nextNode in graph.childrenOf(lastNode):
if nextNode not in tmpPath:
newPath = tmpPath + [nextNode]
pathQueue.append(newPath)
return None
?
Explore all paths with n hops before
exploring any path with more than n hops
33. Want to minimize the sum of the weights of the edges,
not the number of edges
DFS can be easily modified to do this
BFS cannot, since shortest weighted path may have
more than the minimum number of hops
What About a Weighted Shortest Path
6.00.2X LECTURE 3 9
34. Graphs are cool
◦ Best way to create a model of many things
◦ Capture relationships among objects
◦ Many important problems can be posed as graph
optimization problems we already know how to solve
Depth-first and breadth-first search are important
algorithms
◦ Can be used to solve many problems
Recap
6.00.2X LECTURE 3 10
35. Modeling situations with unpredictable events
Will make heavy use of plotting
◦ Lecture 4 is about plotting in Python
◦ Identical to a lecture in 6.00.1x, feel free to skip it if you
took 6.00.1x
Coming Up
6.00.2X LECTURE 3 11