0

I have this wildcard expression pattern and want to resolve to all possible combinations.

pattern = "*{Foo,Bar}{A,B,C,D,E,F,G,H,I,J,K}_{grp,GRP}*"

Comma separated names within curly brackets mean OR, so it should resolve to 2 * 11 * 2 = 44 different wild card strings.

FooA_grp
FooB_GRP
BarA_grp

... and so on

How can I approach this with Python 2.7?

Selcuk
  • 57,004
  • 12
  • 102
  • 110
megaflow
  • 51
  • 3

3 Answers3

2

If this is a cartesian product:

for item in itertools.product(*[['Foo', 'Bar'], ['A','B','C'], ['_'], ['grp', 'GRP']]):  
     print(''.join(item)) 

output:

FooA_grp
FooA_GRP
FooB_grp
FooB_GRP
FooC_grp
FooC_GRP
BarA_grp
BarA_GRP
BarB_grp
BarB_GRP
BarC_grp
BarC_GRP

oppressionslayer
  • 6,942
  • 2
  • 7
  • 24
  • You don't actually need `*[[]]` - `for a, b, c in itertools.product(['Foo', 'Bar'], 'ABC', ['grp', 'GRP']): print(a + b + '_' + c)` works great. – nneonneo Nov 26 '19 at 05:22
0

If you looking to create a possibility list from 3 list item, this will help you

li = ["Foo", "Bar"]
li2 = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"]
li3 = ["grp", "GRP"]

possibility = []

for item in li2:
    p1 = li[0] + item + "_" + li3[0]
    p2 = li[0] + item + "_" + li3[1]
    p3 = li[1] + item + "_" + li3[0]
    p4 = li[1] + item + "_" + li3[1]

    possibility.append(p1)
    possibility.append(p2)
    possibility.append(p3)
    possibility.append(p4)

happy codding

Nj Nafir
  • 570
  • 3
  • 13
0

You can use itertools; specifically itertools.product().

import itertools
list_a = ['Foo', 'Bar']
list_b = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"]
list_c = ["_"]
list_d = ["grp", "GRP"]
combinations = [''.join(element) for element in itertools.product(list_a, list_b, list_c, list_d)]

combinations

FooA_grp
FooA_GRP
FooB_grp
...
BarJ_GRP
BarK_grp
BarK_GRP

Additionaly, if you need to extract the lists list_a, list_b, list_c, and list_d, from the wildcard expression, you can use the re module

import re
exp = "*{Foo,Bar}{A,B,C,D,E,F,G,H,I,J,K}_{grp,GRP}*"
regex = r"\*{(.*)}{(.*)}(_){(.*)}\*"
matched_groups = re.match(regex, exp)
list_a = matched_groups.group(1).split(',')
list_b = matched_groups.group(2).split(',')
list_c = matched_groups.group(3).split(',')
list_d = matched_groups.group(4).split(',')

list_a

['Foo', 'Bar']

list_b

['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K']

list_c

['_']

list_d

['grp', 'GRP']
Arjun Kay
  • 308
  • 1
  • 12