Skip to content

Instantly share code, notes, and snippets.

@senarukana
Created March 20, 2015 13:55
Show Gist options
  • Select an option

  • Save senarukana/9e88ea625af31ac443f2 to your computer and use it in GitHub Desktop.

Select an option

Save senarukana/9e88ea625af31ac443f2 to your computer and use it in GitHub Desktop.
caluclate the number of triangles
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