Search code examples
pythonrandom

How to create rows of non-duplicating strings from a list?


I want to create a 16X4 data frame with these coordinates as strings: "(.1,.1)","(-.1,-.1)","(-.1,.1)","(.1,-.1)". But, I do want not there to be duplicates.

To put it another way, the script would output a 16X4 matrix/dataframe like this:

"(.1,.1)","(-.1,-.1)","(-.1,.1)","(.1,-.1)"
"(-.1,.1)","(-.1,-.1)","(.1,.1)","(.1,-.1)"
"(-.1,-.1)","(.1,.1)","(-.1,.1)","(.1,-.1)" ...

In this way, I would get all the possible combinations of these four coordinates with no column duplicates.

I have been trying to brainstorm solutions. I know I can put them in an array and use random.choice() to randomly sample. But, I am not sure how to form this code in such a way where there will be no column duplicates and that patterns wont repeat.


Solution

  • Those are not strings. They are tuples of floating point values. You're confusing things by using the wrong terminology.

    import itertools
    src = [(.1,.1),(-.1,-.1),(-.1,.1),(.1,-.1)]
    
    for opt in itertools.permutations(src):
        print(opt)
    

    If you really need the permutations in random order, then take the result into a list and shuffle:

    import random
    import itertools
    
    src = [(.1,.1),(-.1,-.1),(-.1,.1),(.1,-.1)]
    def makethem():
        vals = list(itertools.permutations(src))
        random.shuffle(vals)
        return vals[:16]