0

I have a few lines of code that are supposed to order the elements in a list of facets. The facets are lists of vertices and the code orders them such that adjacent elements form an edge, i.e. if a pair of vertices is contained in two facets, the have to be adjacent. Orientation does not matter. The problem is that for loop in the 11th line (see comment) forgets the element of cx that the first for loop has already done.

cx = [[0, 1, 2, 3], [4, 5, 6, 7, 8], [0, 1, 9, 10, 11], [12, 13, 14, 15, 16], [12, 13, 17, 18, 19], [20, 21, 22, 23], [9, 10, 24, 25], [17, 18, 26, 27], [20, 21, 28, 29], [20, 22, 28, 30, 31], [2, 3, 31, 30, 5, 4], [0, 2, 29, 30, 24, 28, 9], [6, 7, 14, 15], [1, 3, 14, 16, 6, 11, 4], [7, 8, 26, 17, 15, 12], [10, 11, 25, 19, 16, 13], [5, 8, 27, 31, 23, 26, 22], [18, 19, 25, 21, 24, 23, 27, 29]] 
ordered = []

for i in range(0,len(cx)):
  ordfacet = []
  facet = cx[i]
  ordfacet.append(facet[0])
  del facet[0]
  while len(facet) > 0:
    for z in facet:
      for y in cx:    #this loop does not iterate over cx[k] for k=0,...,i-1
        if all(x in y for x in [ordfacet[-1],z]):
          ordfacet.append(z)
          facet.remove(z)
          break
  ordered.append(ordfacet)

print(ordered)

Strangely, when I put the definition of cx inside the first for-loop, it works as intended put then I need to know the length of cx to define the range of that first loop which is annoying in practice. Is there a way to do this such that all I need to do is input a list of facets in one place? Thanks.

setarkos
  • 21
  • 3
  • You're mutating `cx` when you mutate `facet`. – Veedrac Jul 03 '16 at 09:19
  • `del facet[0]` deletes from each sublist in `cx` because the reference is shared. Did you want to make a *copy* of `cx` before manipulation? – Martijn Pieters Jul 03 '16 at 09:20
  • I tried calling the initial input `cxx` and then have line `cx = cxx[:]` or `cx = list(cxx)` inside the for-loop but I didn't realise I need to use `cx = copy.deepcopy(cxx)`. Thanks for the pointer. – setarkos Jul 03 '16 at 10:00

0 Answers0