Created
March 20, 2015 13:55
-
-
Save senarukana/9e88ea625af31ac443f2 to your computer and use it in GitHub Desktop.
caluclate the number of triangles
This file contains hidden or 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
| from bisect import bisect_left | |
| def countTriangleTripleIndex(a): | |
| a.sort() | |
| n, count = len(a), 0 | |
| for i in range(n-2): | |
| j = i+1 | |
| k = bisect_left(a, a[i]+a[j])-1 | |
| while k < n: | |
| if k > j and a[i] + a[j] <= a[k]: | |
| count += k-j-1 | |
| j += 1 | |
| else: | |
| k += 1 | |
| count += (k-j) * (k-j-1)/2 | |
| return count | |
| a = [2, 3, 4, 5] | |
| print countTriangleTripleIndex(a) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment