Last active
March 10, 2021 14:32
-
-
Save tuelwer/b7ad6d2e69a823d3302f2f9996f783e6 to your computer and use it in GitHub Desktop.
Short Python script that checks whether a matrix fulfills the triangle inequality
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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