본문 바로가기
Problem Solving/Codility

[Python] 6.4. Triangle

by 부르르 2021. 3. 26.

https://app.codility.com/demo/results/trainingX6JCFR-MQJ/

 

Test results - Codility

An array A consisting of N integers is given. A triplet (P, Q, R) is triangular if 0 ≤ P < Q < R < N and: A[P] + A[Q] > A[R], A[Q] + A[R] > A[P], A[R] + A[P] > A[Q]. For example, consider array A such that: A[0] = 10 A[1] = 2 A[2] = 5 A[3] = 1 A[4] = 8 A

app.codility.com

인풋 데이터의 사이즈가 10만 아래이기 때문에 완전탐색하기로 결정하였다.

순열을 생성해서 모든 경우의 수에 대해서 삼각형 결정조건을 조사하였다.


Task Score

100%

Correctness

100%

Performance

100%

Detected time complexity

O(N * log(N))

def next_perm(a):
    i = len(a)-1

    while i > 0 and a[i-1] >= a[i]:
        i -= 1
    
    if i <= 0:
        return False
    
    j = len(a)-1

    while a[i-1] >= a[j]:
        j -= 1
    
    a[i-1], a[j] = a[j], a[i-1]

    j = len(a)-1

    while i < j:
        a[i], a[j] = a[j], a[i]
        i += 1
        j -= 1

    return True


def solution(A):
    
    if len(A) < 3:
        return 0

    N = len(A)
    _A = sorted(A)
    p = [0]*(N-3) + [1]*3

    while True:
        num = [p[i]*_A[i] for i in range(N) if p[i]*_A[i] > 0]

        if len(num) < 3:
            return 0

        if num[0]+num[1] > num[2] and num[0]+num[2] > num[1] and num[1]+num[2] > num[0]:
            return 1

        if not next_perm(p):
            break

    return 0

 

728x90
반응형

'Problem Solving > Codility' 카테고리의 다른 글

[Python] 7.2. Fish  (0) 2021.03.29
[Python] 7.1. Brackets  (0) 2021.03.27
[Python] 6.3. NumberOfDiscIntersections  (0) 2021.03.25
[Python] 6.2. MaxProductOfThree  (0) 2021.03.25
[Python] 6.1. Distinct  (0) 2021.03.25

댓글