Determine whether a triangle can be built from a given set of edges

/ Published in: Python
Save to your folder(s)

Task description:

Write a function
int triangle(int[] A);
which given a zero-indexed array A of n integers returns 1 if there exists triple i,j,k (, ) such that:

A[i] + A[j] > A[k]

A[i] + A[k] > A[j]

A[j] + A[k] > A[i]
or returns 0 otherwise.

A[0]=10, A[1]=2, A[2]=5, A[3]=1, A[4]=8, A[5]=20
your function should return 1, since for i=0,j=2,k=4 all conditions are fullfiled (i.e. A[2]+A[4]>A[0]).

A[0]=10, A[1]=50, A[2]=5, A[3]=1
your function should return 0.

Copy this code and paste it in your HTML
  1. def triangle ( A ):
  2. # write your code here
  3. A.sort()
  4. for i in range(len(A) - 2):
  5. if A[i] + A[i+1] > A[i+2]:
  6. return 1
  7. return 0


Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.