简体   繁体   中英

Adding same tuple to set results in the creation of permutations of the tuple inserted

I'm trying to create unique arrangements of a 5 element tuple, each element of which is, itself a tuple of two integers. To determine if a given arrangement is unique, I am adding it to a set with the expectation that the set will determine if an arrangement had been previously added that is identical to the new tuple. The following code is what is performing this operation

def generate_each_orientation(self):
    self.orientations = set()
    working = self.raw[:]
    Piece.normalize(working)
    for i in range(8):
        print("Iteration ",i+1)
        print("List to be added to set: ", working)
        self.orientations.add(tuple(working))
        print("Set after adding list:\n",self.orientations)
        [Tile.rotate(t) for t in working]
        Piece.normalize(working)
        if i == 3:
            [Tile.flip(t) for t in working]
            Piece.normalize(working)

The first pass through generates the following output;

Iteration  1
List to be added to set:  [(0, 0), (1, 0), (1, -1), (1, 1), (2, 0)]
Set after adding list:
 {((0, 0), (1, 0), (1, -1), (1, 1), (2, 0))}

Since the set was empty, the first tuple is correctly added. The second iteration of the loop produces

Iteration  2
List to be added to set:  [(0, 0), (1, 0), (1, -1), (1, 1), (2, 0)]
Set after adding list:
 {((1, -1), (1, 0), (2, 0), (0, 0), (1, 1)), ((0, 0), (1, 0), (1, -1), (1, 1), (2, 0))}

Here, even though the input list is identical to that in the first pass, adding it to the set results in a second item with the elements of the tuple having been rearranged. Repeating this 6 more times results in the same behaviour ending with a set that contains 8 items, each with a different permutation of elements in the tuple when it should have only had a single tuple.

What might be happening inside the set add method? Does it take the tuple apart and put it back together in a different order? What can I do to prevent this from occuring?

Look at your set after adding list:

{((0, 0), (1, 0), (1, -1), (1, 1), (2, 0))}

The element is one tuple with 5 tuples inside.

I think you should flatten the set structure (maybe just replace with self.orientations.update(working) if working is a list of tuple?).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM