Skip to content

Instantly share code, notes, and snippets.

@DustinAlandzes
Created January 21, 2018 21:59
Show Gist options
  • Save DustinAlandzes/c2be6dfd1beb35575898a6655766816a to your computer and use it in GitHub Desktop.
Save DustinAlandzes/c2be6dfd1beb35575898a6655766816a to your computer and use it in GitHub Desktop.
from math import log
def arbitrage(table):
transformed_graph = [[-log(edge) for edge in row] for row in graph]
# Pick any source vertex -- we can run Bellman-Ford from any vertex and
# get the right result
source = 0
n = len(transformed_graph)
min_dist = [float('inf')] * n
min_dist[source] = 0
# Relax edges |V - 1| times
for i in range(n - 1):
for v in range(n):
for w in range(n):
if min_dist[w] > min_dist[v] + transformed_graph[v][w]:
min_dist[w] = min_dist[v] + transformed_graph[v][w]
# If we can still relax edges, then we have a negative cycle
for v in range(n):
for w in range(n):
if min_dist[w] > min_dist[v] + transformed_graph[v][w]:
return True
return False
@drbh
Copy link

drbh commented Apr 27, 2019

What does an example input look like?

arbitrage([
    [1.000, 0.013, 0.015],
    [0.013, 1.000, 1.160],
    [0.015, 1.160, 1.000]
])

is this correct? because Im not sure I understand how to format the input for a graph

@drbh
Copy link

drbh commented Apr 27, 2019

Also this article and snippet inspired a Bellman Ford implementation in Rust+wasm: https://github.com/drbh/wasm-bellman-ford

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment