Search code examples
pythonalgorithmconvex-hull

Gift Wrapping algorithm indexing out of range for index > 979


As stated above, I have written a gift-wrapping algorithm:

def giftwrap(listPts):
    """Returns the convex hull vertices computed using the
          giftwrap algorithm as a list of 'h' tuples
          [(u0,v0), (u1,v1), ...]    
    """
    y = 99**99
    #FINDING MIN Y-VAL POINT:
    for i in range(0,len(listPts)):
        if listPts[i][1] < y:
            y = listPts[i][1]
            lowPt = listPts[i]
            k = i
    listPts.append(lowPt) #pts[n] = Pk
    n = len(listPts) -1
    i = 0
    v = 0
    solution = []
    while k != n:
        listPts[i],listPts[k] = listPts[k],listPts[i]
        minAngle = 361
        solution.append(listPts[i])
        for j in range(i+1,n+1):
            angle = theta(listPts[i],listPts[j])
            if(angle < minAngle and angle > v and listPts[j] != listPts[i]):
                minAngle = angle
                k = j
        i = i+1 
        v = minAngle
    return solution

which works correctly for lists of points less than 980. At that number I get an error with this line:

listPts[i],listPts[k] = listPts[k],listPts[i]

I raised an IndexError and found the i value is going to 981 (1 higher than the length of the list) Why would it occur at this integer and integers higher than this?

Note: I tried putting in the following if loop at line 54:

if i != n:
            i = i+1 
            v = minAngle
        else:
            break

However, this returns the solution as a list as all vertices. Thanks


Solution

  • Fixed. I was missing the 0 case in my theta function:

     if t == 0:
        return 360.00