would like to find the shortest path from a source node in the graph to a negative cycle without walking over any cycle twice. If there is a definitive answer to this, please answer. Otherwise, I would like to show how I have approached the problem in the hope that others may show me where I have erred. Nov 13, 2018 in Python 793 views

## 1 answer to this question.

```class NegativeWeightFinder:
def __init__(self, graph: nx.Graph):
self.graph = graph
self.predecessor_to = {}
self.distance_to = {}

def initialize(self, source):
for node in self.graph:
# Initialize all distance_to values to infinity and all predecessor_to values to None
self.distance_to[node] = float('Inf')
self.predecessor_to[node] = None

# The distance from any node to (itself) == 0
self.distance_to[source] = 0

def bellman_ford(self, source):

self.initialize(source)
for i in range(len(self.graph) - 1):
for edge in self.graph.edges(data=True):
self.relax(edge)

for edge in self.graph.edges(data=True):
if self.distance_to[edge] + edge['weight'] <
self.distance_to[edge]:
yield self._retrace_negative_loop(edge)```

I have also implemented a method to retrace negative loops:

```def _retrace_negative_loop(self, start):
loop = [start]
while True:
next_node = self.predecessor_to[next_node]
# if negative cycle is complete
if next_node in loop:
loop = loop[:loop.index(next_node) + 1]
loop.insert(0, next_node)
return loop``` answered Nov 13, 2018 by
• 3,540 points

## I have a file of type text and fields separated with 'tab' so how to get avroschema from input text file in python

i have textfile now i want to ...READ MORE

+1 vote

## I am trying to write a program in python for the occurrences of a character given the start and stop values of that string only using while

Here's the code: check = input("Enter the character: ...READ MORE

## how do i change string to a list?

suppose you have a string with a ...READ MORE

## how can i randomly select items from a list?

You can also use the random library's ...READ MORE

+1 vote

## how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE