试图生成一系列独特的随机数

时间:2013-09-10 15:16:16

标签: python random

很抱歉,如果这很明显,我很新。

这是代码。 它应该永远不会打印出我理解的相同的两件事,但它有时会这样做。关键是p1为1应该防止p2为1,如果p2为1,则p2应该以相同的p1值再次运行,但是应该生成一个新的随机数。它可能再次为1,但是函数应该继续返回并运行直到它们不同,对吧?

#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()

4 个答案:

答案 0 :(得分:9)

不是选择随机整数,而是随机抽取列表并选择前两项:

import random

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

item1, item2 = choices[:2]

因为我们首先将可能的选项列表混乱,然后选择前两个,您可以保证item1item2永远不会彼此相等。

使用random.shuffle()使选项保持打开以对剩余选项执行某些操作;你只有1个,但在更大的集合中,你可以继续选择迄今为止尚未被选中的项目:

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())

会给你100个随机数而不重复。

如果您只需要随机抽样2,请改用random.sample()

import random

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

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

答案 1 :(得分:4)

您可以使用Python中的random模块为您做繁重的工作,特别是random.sample()

>>> import random
>>> random.sample(['candy', 'steak', 'vegetable'], 2)
['vegetable', 'steak']

答案 2 :(得分:0)

如果你想保留原始逻辑,这里有一些伪代码:

while(P2Local == A)
   P2Local = random.randint(1,3)

答案 3 :(得分:0)

from random import choice
x = ['foo','bar','fight']
num_uniq = 2
uniq_rand = set()
while len(uniq_rand) < num_uniq:
  uniq_rand.add(choice(x))
print uniq_rand

正如@Martijn指出的那样,这肯定不如random.sample() =)

效率高
相关问题