Generate all subsets of size k (containing k elements) in Python

前端 未结 3 805
后悔当初
后悔当初 2020-12-03 14:31

I have a set of values and would like to create list of all subsets containing 2 elements.

For example, a source set ([1,2,3]) has the following 2-elem

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-03 14:47

    Just to give another perspective, I looked for a way to iterate all subset of size 2 of {1.....N}, so I put itertools.combinations into test:

    import itertools
    from time import time
    
    
    N = 7000
    lst = [i for i in xrange(N)]
    
    st = time()
    c1 = 0
    for x in itertools.combinations(lst, 2):
        c1 += 1
    print "combinations: %f" % (time()-st)
    
    st = time()
    c2=0
    for x in xrange(N):
        for y in xrange(x):
            c2 += 1
    print "double loop: %f" % (time()-st)
    print "c1=%d,c2=%d" % (c1,c2)
    
    # prints:
    #combinations: 4.247000
    #double loop: 3.479000
    # c1=24496500,c2=24496500
    

    So I guess you should not always turn into the general solution.... If you know in advance the size of the subset you want, it should be more efficient to iterate using for loops.

    Also note that you should not iterate over list(itertools.combinations(lst, 2)) since this move creates the list (and much slower than using the generator itself).

提交回复
热议问题