简体   繁体   中英

Python - 5 digit random number generator with no repeating digits

I am supposed to print a random 5-digit number with no repeating digits, then ask the user for a three digit number. If the user's number contains three digits from the random number, print "correct".

I am using this code for the random number

num = random.randint (0,99999)
print (num)

The problem is it will not always print a five digit number.

Also, I don't know how to match the user number with the random number.

Thank you.

随机抽取数字0到9:

''.join(random.sample('0123456789', 5))

Use zfill and set like so: Edited to account for numbers with repeating digits

import random


def threeInFive(user_num):
    num = str(random.randint(0, 99999)).zfill(5)
    num = ''.join(set([n for n in num]))
    if len(num) < 5:
        print "There were repeating digits...trying again"
        threeInFive(user_num)
    elif str(user_num) in num:
        print "The user number is in there!"
        return True
    else:
        print "The user number : %s is not in : %s" % (user_num, num)
        return False

threeInFive(500)

You can generate all the 5 digits ints with unique digits like so:

tgt=set()
for i in range(1234,99999+1):
    s='{:05d}'.format(i)
    if len(set(s))==5:
        tgt.add(s)  

Then use random.choose(tgt) to select one at random.

(but tdelaney's answer is better)

If you generate your numbers like this:

larger_number = ''.join(random.sample(string.digits, 5))

And got the numbers from the user like this:

def get_user_num(length=5):
    while True:
        num = raw_input('Enter a {}-digit number with no repeating digits: '.format(length)).zfill(length)
        if len(set(num)) < length:
            print('Please try again.')
            continue
        else:
            return num

You could determine if the user's numbers were in the number list like so:

set(user_number) < set(larger_number)

And then it would be a really simple matter to combine this all together into a program. Note that the numbers are never actually treated as numbers - they're just strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM