Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Trying to generate a series of unique random numbers

Sorry if this is obvious, im pretty new.

Here is the code. It should never print the same two things as i understand it, but it sometimes does. The point is that p1 being 1 should prevent p2 from being 1, and if p2 is 1, p2 should run again with the same p1 value, but should generate a new random number. It might be 1 again, but then the function should just keep returning else and running until they're different, right?

#Random Test with Exclusion
P1Item = 'Empty'
P2Item = 'Empty'
import random
import time

def P1():
    global P1Item
    global P2Exclusion
    P1Local = random.randint(1,3)
    if P1Local == 1:
        P1Item = 'Candy'
        P2(P1Local)
    elif P1Local == 2:
        P1Item = 'Steak'
        P2(P1Local)
    elif P1Local == 3:
        P1Item = 'Vegetables'
        P2(P1Local)


def P2(A):
    global P2Item
        P2Local = random.randint(1,3)
        if P2Local == 1 and A != 1:
            P2Item = 'Candy'
        elif P2Local == 2 and A != 2:
            P2Item = 'Steak'
        elif P2Local == 3 and A != 3:
        P3Item = 'Vegetables'
        else:
            B = A
            P2(B)

def Test():
    print('Test')
    print('Define')
    P1()
    print(P1Item + ' ' + P2Item)
    time.sleep(1)
    input()
    Test()

Test()
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Instead of picking random integers, shuffle a list and pick the first two items:

import random

choices = ['Candy', 'Steak', 'Vegetables']
random.shuffle(choices)

item1, item2 = choices[:2]

Because we shuffled a list of possible choices first, then picked the first two, you can guarantee that item1 and item2 are never equal to one another.

Using random.shuffle() leaves the option open to do something with the remaining choices; you only have 1 here, but in a larger set you can continue to pick items that have so far not been picked:

choices = list(range(100))
random.shuffle(choices)
while choices:
    if input('Do you want another random number? (Y/N)' ).lower() == 'n':
        break
    print(choices.pop())

would give you 100 random numbers without repeating.

If all you need is a random sample of 2, use random.sample() instead:

import random

choices = ['Candy', 'Steak', 'Vegetables']

item1, item2 = random.sample(choices, 2)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...