Fix a function returning duplicates over time?

2019-09-30 07:34发布

I have a function here that returns a 4 digit string. The problem is that when I run the function like 500 times or more, it starts to return duplicates. How to avoid that?

My Function:

import random
def CreatePass():
    Num = str(random.randint(1000, 9999)
    return Num

标签: python random
4条回答
萌系小妹纸
2楼-- · 2019-09-30 08:10

A random sequence without duplicates isn't random.

You can reduce the likelihood of duplicates by increasing the range of possible values.

Alternatively, you can record previous return values, and choose a new value if it has been previously returned.

Finally, you could generate the whole sequence, then shuffle it.

Of course, you then need to figure out what to do once you have exhausted the possible return values, as well as the whether the behaviour once there are only a small number of possible return values is actually desirable.

Also, you should comply with standard Python coding standards.

查看更多
孤傲高冷的网名
3楼-- · 2019-09-30 08:17

Generate a list, shuffle that and pop from it each time the function is called:

import random

def CreatePass(_numbers=[]):
    if not _numbers:
        _numbers[:] = range(1000, 10000)
        random.shuffle(_numbers)              
    return str(_numbers.pop())

Note that this re-generates the _numbers list once you've run out, but then you've used up all 8999 possible numbers and would have to accept repetitions anyway.

查看更多
疯言疯语
4楼-- · 2019-09-30 08:20

Could just roll your own, and hope not to exhaust it:

from random import shuffle
def myrandom(start, end):
    possible = range(start, end)
    shuffle(possible)
    for i in possible:
        yield str(i)

randoms = myrand(1000, 9999)
print next(randoms)
print next(randoms)
# etc...

You'll get a StopIteration when it's exhausted though...

查看更多
女痞
5楼-- · 2019-09-30 08:33

@Martijn's solution is enough since you only need to store and shuffle 9000 numbers. If you want numbers from a bigger range and you know (approximately) how many numbers you'll need, there's a better way: The function random.sample will give you numbers in the desired range without repetition. For example, to get 500 distinct six-digit numbers you'd use:

selected = random.sample(xrange(100000, 1000000), 500)
查看更多
登录 后发表回答