Skip to content

Instantly share code, notes, and snippets.

@tuelwer
Last active March 10, 2021 14:32
Show Gist options
  • Save tuelwer/b7ad6d2e69a823d3302f2f9996f783e6 to your computer and use it in GitHub Desktop.
Save tuelwer/b7ad6d2e69a823d3302f2f9996f783e6 to your computer and use it in GitHub Desktop.
Short Python script that checks whether a matrix fulfills the triangle inequality
def check_triangle_inequality(D):
""" Returns true iff the matrix D fulfills
the triangle inequaltiy.
"""
n = len(D)
valid = True
for i in range(n):
for j in range(i, n):
for k in range(n):
if k == j or k == i:
continue
if D[i][j] > D[i][k] + D[k][j]:
print('Invalid triple:', i, k, j)
valid = False
return valid
if __name__ == '__main__':
D = [[0, 3, 5, 9, 2],
[3, 0, 4, 7, 1],
[5, 4, 0, 8, 6],
[9, 7, 8, 0, 9],
[2, 1, 6, 9, 0]]
print(check_triangle_inequality(D))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment