Create a random order of (x, y) pairs, without repeating/subsequent x's

后端 未结 9 2256
陌清茗
陌清茗 2021-02-08 12:25

Say I have a list of valid X = [1, 2, 3, 4, 5] and a list of valid Y = [1, 2, 3, 4, 5].

I need to generate all combinations of every element in

9条回答
  •  别那么骄傲
    2021-02-08 12:58

    For completeness, I guess I will throw in the super-naive "just keep shuffling till you get one" solution. It's not guaranteed to even terminate, but if it does, it will have a good degree of randomness, and you did say one of the desired qualities was succinctness, and this sure is succinct:

    import itertools
    import random
    
    x = range(5)  # this is a list in Python 2
    y = range(5)
    all_pairs = list(itertools.product(x, y))
    
    s = list(all_pairs)  # make a working copy
    while any(s[i][0] == s[i + 1][0] for i in range(len(s) - 1)):
        random.shuffle(s)
    print s
    

    As was commented, for small values of x and y (especially y!), this is actually a reasonably quick solution. Your example of 5 for each completes in an average time of "right away". The deck of cards example (4 and 13) can take much longer, because it will usually require hundreds of thousands of shuffles. (And again, is not guaranteed to terminate at all.)

提交回复
热议问题