Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

python - Fix a function returning duplicates over time?

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...