File: cart.py

package info (click to toggle)
singular 1%3A4.1.1-p2%2Bds-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 35,856 kB
  • sloc: cpp: 288,280; ansic: 17,387; lisp: 4,242; yacc: 1,654; python: 1,608; makefile: 1,424; lex: 1,387; perl: 632; sh: 567; xml: 182
file content (26 lines) | stat: -rw-r--r-- 1,128 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import itertools
def xcombine(*seqin):
    '''returns a generator which returns combinations of argument sequences
for example xcombine((1,2),(3,4)) returns a generator; calling the next()
method on the generator will return [1,3], [1,4], [2,3], [2,4] and
StopIteration exception.  This will not create the whole list of
combinations in memory at once.'''
    def rloop(seqin,comb):
        '''recursive looping function'''
        if seqin:                   # any more sequences to process?
            for item in seqin[0]:
                newcomb=comb+[item]     # add next item to current combination
                # call rloop w/ remaining seqs, newcomb
                for item in rloop(seqin[1:],newcomb):
                    yield item          # seqs and newcomb
        else:                           # processing last sequence
            yield comb                  # comb finished, add to list
    return rloop(seqin,[])

def cartn(sequence, n):
  tocombine=list(itertools.repeat(sequence,n))
  return itertools.imap(tuple,xcombine(*tocombine))

if __name__=='__main__':
  for i in cartn([1,2,3],4):
    print i