2

I am very new to Python and was surprised to find that this section of my code:

print len(allCommunities[5].boundary)
allCommunities[5].surface = triangularize(allCommunities[5].boundary)
print len(allCommunities[5].boundary)

Outputs this:

1310
2

Below is a function I wrote in Processing (a language like Java) and ported into Python. It does what it is supposed to (triangulate a polygon) but my intention was to pass inBoundary for the function to use but not remove elements from allCommunities[5].boundary.

How should I go about preventing allCommunities[5].boundary from being modified in the function? On a side note, I would appreciate pointers if I am doing something silly otherwise in the function, still getting used to Python.

def triangularize(inBoundary):
    outSurface = []

    index = 0;
    while len(inBoundary) > 2:
        pIndex = (index+len(inBoundary)-1)%len(inBoundary);
        nIndex = (index+1)%len(inBoundary);

        bp = inBoundary[pIndex]
        bi = inBoundary[index]
        bn = inBoundary[nIndex]

        # This assumes the polygon is in clockwise order
        theta = math.atan2(bi.y-bn.y, bi.x-bn.x)-math.atan2(bi.y-bp.y, bi.x-bp.x);
        if theta < 0.0: theta += math.pi*2.0;

        # If bp, bi, and bn describe an "ear" of the polygon
        if theta < math.pi:
            inside = False;

            # Make sure other vertices are not inside the "ear"
            for i in range(len(inBoundary)):
                if i == pIndex or i == index or i == nIndex: continue;

                # Black magic point in triangle expressions
                # http://answers.yahoo.com/question/index?qid=20111103091813AA1jksL
                pi = inBoundary[i]
                ep = (bi.x-bp.x)*(pi.y-bp.y)-(bi.y-bp.y)*(pi.x-bp.x)
                ei = (bn.x-bi.x)*(pi.y-bi.y)-(bn.y-bi.y)*(pi.x-bi.x)
                en = (bp.x-bn.x)*(pi.y-bn.y)-(bp.y-bn.y)*(pi.x-bn.x)

                # This only tests if the point is inside the triangle (no edge / vertex test)
                if (ep < 0 and ei < 0 and en < 0) or (ep > 0 and ei > 0 and en > 0):
                    inside = True;
                    break

            # No vertices in the "ear", add a triangle and remove bi
            if not inside:
                outSurface.append(Triangle(bp, bi, bn))
                inBoundary.pop(index)
        index = (index+1)%len(inBoundary)
    return outSurface

print len(allCommunities[5].boundary)
allCommunities[5].surface = triangularize(allCommunities[5].boundary)
print len(allCommunities[5].boundary)
4

2 回答 2

4

Python 中的列表是可变的,诸如

inBoundary.pop

修改它们。简单的解决方案是复制函数内的列表:

def triangularize(inBoundary):
    inBoundary = list(inBoundary)
    # proceed as before
于 2013-09-19T07:58:26.153 回答
3

最简单的做法是复制传入的参数:

def triangularize(origBoundary):
    inBoundary = origBoundary[:]

然后您的其余代码可以保持不变。

于 2013-09-19T07:58:22.573 回答