How to generate random pairs of numbers in Python, including pairs with one entry being the same and excluding pairs with both entries being the same?

前端 未结 3 1251
北恋
北恋 2021-02-06 07:26

I\'m using Python and was using numpy for this. I want to generate pairs of random numbers. I want to exclude repetitive outcomes of pairs with both entries being the s

3条回答
  •  温柔的废话
    2021-02-06 07:40

    @James Miles answer is great, but just to avoid endless loops when accidentally asking for too many arguments I suggest the following (it also removes some repetitions):

    def gencoordinates(m, n):
        seen = set()
        x, y = randint(m, n), randint(m, n)
        while len(seen) < (n + 1 - m)**2:
            while (x, y) in seen:
                x, y = randint(m, n), randint(m, n)
            seen.add((x, y))
            yield (x, y)
        return
    

    Note that wrong range of values will still propagate down.

提交回复
热议问题