Reputation: 37
I am trying to create a combination of unique phrases to make a sentence and want to randomly select a phrase length from S (only needs to happen 1 time), and then randomly select first a J value, and then a random Q value, but I do not want the same value selected from J or S selected. How can I do this?
Here is what some of the sample outputs look like:
I3 and I1 I4 not I5 I5 or I4 and I3 not I3
Q=("but","why","okay")
J=("J1","J2","J3","J4","J5")
S=[(J), (J,Q,J), (J,Q,J,Q,J),(J,Q,J,Q,J,Q,J)]
' '.join([random.choice(i) for i in random.choice(S)])
Upvotes: 0
Views: 163
Reputation: 198526
Shuffle both arrays, then take elements as you need, one by one. Or sample them, if you don't want to have the originals perturbed:
Q=("but","why","okay")
J=("J1","J2","J3","J4","J5")
S=[(J,), (J,Q,J), (J,Q,J,Q,J), (J,Q,J,Q,J,Q,J)]
from random import sample, choice
from collections import Counter
seq = choice(S)
iters = { s: iter(sample(s, c)) for s, c in Counter(seq).items() }
result = ' '.join(next(iters[s]) for s in seq)
So I pick the desired sequence first. Then I count how many times does each list appear in the chosen sequence. Then, for each unique list, I take as many random elements (without repetition) as there are appearances of the list in the sequence, then make an iterator for those choices, so I can get them one by one. The last thing left to do is to iterate over the sequence, and take the next element from the appropriate iterator.
Upvotes: 1
Reputation: 76
I hope it helps
result = []
temp = S
while temp is not empty:
random1 = random.choice(temp)
value = random.choice(random1)
result.append(value)
temp2 = random1.remove(value)
temp = temp.remove(random1)
if temp2 is not empty:
temp = temp.append(temp2)
print(' '.join(result))
The key idea is that we will remove the chosen value before the next random
Upvotes: 0