So lets say I have a python list:
num_list = ["3", "2", "5", "6", "9", "3", "0"]
What I want to do is: each time select a sample with 5 numbers from this list; the first number can only be 0, 3, or 9.
How can I write an algorithm in python find all the combinations that can be sampled from the list with the above two conditions?
I have used the random module in python, but it can't do restricted sample selection like the condition for first number being only 0, 3 or 9.
You don't need to sample from all the combinations (which would quickly become prohibitive as you increase the number of items). Instead, separate the selection of the first item from sampling of the rest. To do so, select the first number from a random choice of the indexes that contain 0, 3 or 9. Then pick a sample of 4 from the remaining positions
nums = ["3", "2", "5", "6", "9", "3", "0"]
import random
firstIndexes = [i for i,n in enumerate(nums) if n in "039"]
for _ in range(10):
i0 = random.choice(firstIndexes)
result = (nums[i0],*random.sample(nums[:i0]+nums[i0+1:],4))
print(result)
('9', '2', '0', '6', '5')
('3', '0', '6', '2', '9')
('9', '5', '3', '3', '2')
('3', '0', '9', '3', '5')
('9', '0', '2', '3', '6')
('3', '6', '5', '2', '3')
('0', '9', '3', '3', '6')
('3', '2', '3', '9', '6')
('9', '3', '6', '2', '3')
('9', '5', '0', '2', '3')