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 1212
北恋
北恋 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:31

    Generator random unique coordinates:

    from random import randint
    
    def gencoordinates(m, n):
        seen = set()
    
        x, y = randint(m, n), randint(m, n)
    
        while True:
            seen.add((x, y))
            yield (x, y)
            x, y = randint(m, n), randint(m, n)
            while (x, y) in seen:
                x, y = randint(m, n), randint(m, n)
    

    Output:

    >>> g = gencoordinates(1, 100)
    >>> next(g)
    (42, 98)
    >>> next(g)
    (9, 5)
    >>> next(g)
    (89, 29)
    >>> next(g)
    (67, 56)
    >>> next(g)
    (63, 65)
    >>> next(g)
    (92, 66)
    >>> next(g)
    (11, 46)
    >>> next(g)
    (68, 21)
    >>> next(g)
    (85, 6)
    >>> next(g)
    (95, 97)
    >>> next(g)
    (20, 6)
    >>> next(g)
    (20, 86)
    

    As you can see coincidentally an x coordinate was repeated!

提交回复
热议问题