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()
As @Martijn pointed out, this is not surely not as efficient as
random.sample()
=)Instead of picking random integers, shuffle a list and pick the first two items:
Because we shuffled a list of possible choices first, then picked the first two, you can guarantee that
item1
anditem2
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:would give you 100 random numbers without repeating.
If all you need is a random sample of 2, use
random.sample()
instead:if you want to keep the original logic, here is some pseudo code:
You can use the
random
module in Python to do the heavy lifting for you, specificallyrandom.sample()
: