Search code examples
pythonline-breaks

Python: Print permutations of 4 variables


I found this Python script that prints all permutations of given variables. I am a complete Python newby, but after a few modifications it does almost exactly what I need.

Here is what I got so far:

blocks =  [ "0", "1a", "2a", "2b" ] # variables
num_blocks = len( blocks )
num_places = 4  # number of places

for i in range( pow( len( blocks ), num_places ) ): 
    value = i
    indexes = []

    while value:    
        indexes.append( value % num_blocks )
        value = value // num_blocks

    # print( i + 1 ) # alternatively print number of each permutation

    for j in range( len( indexes ), num_places ):
        print blocks[ num_blocks - 1 ]

    for j in range( len( indexes ) - 1, -1, -1 ):
        print( blocks[ num_blocks - 1 - indexes[ j ] ] )

    print " "  # add a line break after each entry

The output is

2b
2b
2b
2b

2b
2b
2b
2a

etc.

How can I A) change the output to

2b2b2b2b
2b2b2b2a

etc.

and B) only print occurences that include the last variable, in this case "2b". For the purpose of this example, I only included four variables: 0, 1a, 2a, 2b. The script prints all possible combinations of these four variables, from 0000 to 2b2b2b2b and anything in between. Is it possible to print only combinations that include the last variable 2b? So for example 2b2a1a0 or 1a1a02b, but not 2a2a1a0 or 2a01a1a? Later on, many more variables will be included (3a, 3b, etc.), but the script shall only list permutations including the last variable.

Thanks in advance!

George

EDITED to clarify second question.


Solution

  • Updated: This will clarify both of your questions. Thanks.

    blocks =  [ "0", "1a", "2a", "2b" ] # variables
    num_blocks = len( blocks )
    num_places = 4  # number of places
    
    for i in range( pow( len( blocks ), num_places ) ): 
      value = i
      indexes = []
    
      while value:    
          indexes.append(value % num_blocks)
          value = value // num_blocks
    
      # print( i + 1 ) # alternatively print number of each permutation
      
      output = ''
      for j in range( len( indexes ), num_places ):
          output +=  str(blocks[ num_blocks - 1 ])
      
      for j in range( len( indexes ) - 1, -1, -1 ):
          output += str(blocks[ num_blocks - 1 - indexes[j] ])
      
      search = blocks[3] # search '2b' in output
      if output.find(search) != -1 :
          print output,
          print " "