Generating non-repeating random numbers in Python

前端 未结 17 1750
粉色の甜心
粉色の甜心 2020-11-30 19:56

Ok this is one of those trickier than it sounds questions so I\'m turning to stack overflow because I can\'t think of a good answer. Here is what I want: I need Python to ge

17条回答
  •  一向
    一向 (楼主)
    2020-11-30 20:38

    If they don't have to be random, but just not obviously linear (1, 2, 3, 4, ...), then here's a simple algorithm:

    Pick two prime numbers. One of them will be the largest number you can generate, so it should be around one billion. The other should be fairly large.

    max_value = 795028841
    step = 360287471
    previous_serial = 0
    for i in xrange(0, max_value):
        previous_serial += step
        previous_serial %= max_value
        print "Serial: %09i" % previous_serial
    

    Just store the previous serial each time so you know where you left off. I can't prove mathmatically that this works (been too long since those particular classes), but it's demonstrably correct with smaller primes:

    s = set()
    with open("test.txt", "w+") as f:
        previous_serial = 0
        for i in xrange(0, 2711):
            previous_serial += 1811
            previous_serial %= 2711
            assert previous_serial not in s
            s.add(previous_serial)
    

    You could also prove it empirically with 9-digit primes, it'd just take a bit more work (or a lot more memory).

    This does mean that given a few serial numbers, it'd be possible to figure out what your values are--but with only nine digits, it's not likely that you're going for unguessable numbers anyway.

提交回复
热议问题