Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading