Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9142467
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T09:47:23+00:00 2026-06-17T09:47:23+00:00

I’ve been having a go at writing the Bellman Ford algoritm for finding the

  • 0

I’ve been having a go at writing the Bellman Ford algoritm for finding the shortest path in a graph and while I’ve got a working solution it doesn’t run very quickly and I’m led to believe it could be faster if I use numpy instead of my current approach.

This is the solution I have using for loops:

import os                    
file = open(os.path.dirname(os.path.realpath(__file__)) + "/g_small.txt")

vertices, edges = map(lambda x: int(x), file.readline().replace("\n", "").split(" "))

adjacency_list = [[] for k in xrange(vertices)]
for line in file.readlines():
    tail, head, weight = line.split(" ")
    adjacency_list[int(head)-1].append({"from" : int(tail), "weight" : int(weight)})

n = vertices

shortest_paths = []
s=2

cache = [[0 for k in xrange(vertices)] for j in xrange(vertices)]
cache[0][s] = 0

for v in range(0, vertices):
    if v != s:
    cache[0][v] = float("inf")

# this can be done with numpy I think?
for i in range(1, vertices):
    for v in range(0, vertices):
        adjacent_nodes = adjacency_list[v]

        least_adjacent_cost = float("inf")
        for node in adjacent_nodes:
            adjacent_cost = cache[i-1][node["from"]-1] + node["weight"]
            if adjacent_cost < least_adjacent_cost:
                least_adjacent_cost = adjacent_cost

        cache[i][v] = min(cache[i-1][v], least_adjacent_cost)

shortest_paths.append([s, cache[vertices-1]])

for path in shortest_paths:
    print(str(path[1]))

shortest_path = min(reduce(lambda x, y: x + y, map(lambda x: x[1], shortest_paths)))  
print("Shortest Path: " + str(shortest_path))  

The input file looks like this -> https://github.com/mneedham/algorithms2/blob/master/shortestpath/g_small.txt

It’s mostly uninteresting except for the nested loops about half way down. I’ve tried to vectorise it using numpy but I’m not really sure how to do it given that the matrix/2D array gets changed on each iteration.

If anyone has any ideas on what I need to do or even something to read that would help me on my way that’d be awesome.

==================

I wrote an updated version to take Jaime’s comment into account:

s=0

def initialise_cache(vertices, s):
    cache = [0 for k in xrange(vertices)]
    cache[s] = 0

    for v in range(0, vertices):
        if v != s:
            cache[v] = float("inf")
    return cache    

cache = initialise_cache(vertices, s)

for i in range(1, vertices):
    previous_cache = deepcopy(cache)
    cache = initialise_cache(vertices, s)
    for v in range(0, vertices):
        adjacent_nodes = adjacency_list[v]

    least_adjacent_cost = float("inf")
    for node in adjacent_nodes:
        adjacent_cost = previous_cache[node["from"]-1] + node["weight"]
        if adjacent_cost < least_adjacent_cost:
            least_adjacent_cost = adjacent_cost

    cache[v] = min(previous_cache[v], least_adjacent_cost)

================

And another new version this time using vectorisation:

def initialise_cache(vertices, s):
    cache = empty(vertices)
    cache[:] = float("inf")
    cache[s] = 0
    return cache    

adjacency_matrix = zeros((vertices, vertices))
adjacency_matrix[:] = float("inf")
for line in file.readlines():
    tail, head, weight = line.split(" ")
    adjacency_matrix[int(head)-1][int(tail)-1] = int(weight)    

n = vertices
shortest_paths = []
s=2

cache = initialise_cache(vertices, s)
for i in range(1, vertices):
    previous_cache = cache
    combined = (previous_cache.T + adjacency_matrix).min(axis=1)
    cache = minimum(previous_cache, combined)

shortest_paths.append([s, cache])
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T09:47:24+00:00Added an answer on June 17, 2026 at 9:47 am

    I ended up with the following vectorised code after following Jaime’s advice:

    def initialise_cache(vertices, s):
        cache = empty(vertices)
        cache[:] = float("inf")
        cache[s] = 0
        return cache    
    
    adjacency_matrix = zeros((vertices, vertices))
    adjacency_matrix[:] = float("inf")
    for line in file.readlines():
        tail, head, weight = line.split(" ")
        adjacency_matrix[int(head)-1][int(tail)-1] = int(weight)    
    
    n = vertices
    shortest_paths = []
    s=2
    
    cache = initialise_cache(vertices, s)
    for i in range(1, vertices):
        previous_cache = cache
        combined = (previous_cache.T + adjacency_matrix).min(axis=1)
        cache = minimum(previous_cache, combined)
    
    shortest_paths.append([s, cache])
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a jquery bug and I've been looking for hours now, I can't
I've got a string that has curly quotes in it. I'd like to replace
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
I have been unable to fix a problem with Java Unicode and encoding. The
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
i got an object with contents of html markup in it, for example: string
I am writing an app with both english and french support. The app requests
I'm having trouble keeping the paragraph square between the quote marks. In firefox the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.