Home > Mobile >  How to make a python script that gives you every iteration of a string from a pattern
How to make a python script that gives you every iteration of a string from a pattern

Time:11-09

So I'm trying to make a python script that takes a pattern (ex: c**l) where it'll return every iteration of the string (* = any character in the alphabet)...

So, we get something like: caal, cbal, ccal and so forth. I've tried using the itertools library's product but I haven't been able to make it work properly. So after 2 hours I've decide to turn to Stack Overflow.

Here's my current code. It's not complete since I feel stuck

alphabet = list('abcdefghijklmnopqrstuvwxyz')

wildChar = False
tmp_string = ""
combinations = []

if '*' in pattern:
    wildChar = True
    tmp_string = pattern.replace('*', '', pattern.count('*') 1)

if wildChar:
    tmp = []
    for _ in range(pattern.count('*')):
        tmp.append(list(product(tmp_string, alphabet)))
    
        for array in tmp:
            for instance in array:
                
                combinations.append("".join(instance))
                tmp = []

print(combinations)

CodePudding user response:

You could try:

from itertools import product
from string import ascii_lowercase

pattern = "c**l"
repeat = pattern.count("*")
pattern = pattern.replace("*", "{}")
for letters in product(ascii_lowercase, repeat=repeat):
    print(pattern.format(*letters))

Result:

caal
cabl
cacl
...
czxl
czyl
czzl

CodePudding user response:

Use itertools.product

import itertools
import string

s = 'c**l'
l = [c if c != '*' else string.ascii_lowercase) for c in s]
out = [''.join(c) for c in itertools.product(*l)]

Output:

>>> out
['caal',
 'cabl',
 'cacl',
 'cadl',
 'cael',
 'cafl',
 'cagl',
 'cahl',
 'cail',
 'cajl'
 ...
  • Related