Mark Gritter (markgritter) wrote,
Mark Gritter

Python programming problem

Suppose you have a set A and you want all possible ordered triples of elements in A. In Python you can just do

for x in itertools.product( A, repeat = 3 )

Now, what if A has a special element X and you want only the ordered triples that include at least one X. What's the best way of doing so? (Assuming we want to pick only among the implementations which don't generate all triples and then filter.)

I was thinking of

A = complete set
X = mandatory element
Aprime = A - X

for i in xrange( 0, 3 ):
  allowed = [ Aprime ] * i + [ [ X ] ] + [ A ] * ( 3 - i - 1 )
  for x in itertools.product( *allowed ):
     yield x

but this seems a bit indirect (of course, I'm allowing for the general case here.) The idea is to iterate over (X, any, any), then (not X, X, any) then (not X, not X, X) which should cover all possibilities exactly once.

Other alternatives?
Tags: combinatorics, programming
  • Post a new comment


    default userpic

    Your reply will be screened

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.