python - Shuffling combinations without converting iterable (itertools.combinations) to list -


the following simple code gives me possible combinations of length 3 of 200 elements.

from itertools import combinations comb = combinations( range(200), 3 ) 

i want combinations in random order in order pick first n combinations. however, if convert comb list , shuffle following, may memory error because list might contain many elements:

comb = list(comb) # might huge , give memory error  random.shuffle(comb) n = 10 comb = comb[:10] # first n random combinations 

is there other way n random combinations ? (i.e., not in order generated itertools.combinations).

there c(200, 3) = 1313400 possible combinations. mentioned, number can out of hand due combinatorial explosion. example, if choose 4 instead of 3 elements, number of combinations approximately 50 times larger (64684950). instead of randomly selecting these combinations, can randomly build possible combinations.

to build combinations, can use random.sample random library. random.sample(range(200), 3) randomly generate 1 of 1313400 combinations. if call again, generate combination.

there 2 issues:

  1. order important in random.sample ([1, 2, 3] different [1, 3, 2]). in combinations, not. solve that, can use sorted().
  2. random.sample independently generate next 3 numbers. therefore, combinations generated in different iterations same. although unlikely example (≈0.0000343), can use set store combinations unique combinations stored.

the following generate 10 different combinations:

import random combs = set() n = 10 while len(combs) < n:     combs.add(tuple(sorted(random.sample(range(200), 3)))) 

Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -