Ad

Python How To Generate Permutations Of Putting A Singular Character Into A Word

No idea how to word this so the title sucks my bad,

Basically, I have a 4 letter word and I want to generate every permutation of putting a dash in it.

So if my word was Cats, I want to get every permutation of it having a dash in it,

Example:

c-ats
ca-ts
-c-ats
etc,

Is anybody able to help me?

Ad

Answer

I assume that you want to generate all possible ways to insert zero or more hyphens into your word s.t. no two hyphens are adjacent. Here is one way to do this with itertools.product:

from itertools import product

def hyphens(word):
  # create template, each {} is to be filled with "" or "-"
  template = "{}" + "{}".join(word) + "{}"
  # iterate over all possible ways to fill empty braces
  for chars in product(["", "-"], repeat=len(word) + 1):
    yield template.format(*chars)

list(hyphens('cats'))
# ['cats', 'cats-', 'cat-s', 'cat-s-', 'ca-ts', 'ca-ts-', 'ca-t-s', 'ca-t-s-', 
# 'c-ats', 'c-ats-', 'c-at-s', 'c-at-s-', 'c-a-ts', 'c-a-ts-', 'c-a-t-s', 
# 'c-a-t-s-', '-cats', '-cats-', '-cat-s', '-cat-s-', '-ca-ts', '-ca-ts-', 
# '-ca-t-s', '-ca-t-s-', '-c-ats', '-c-ats-', '-c-at-s', '-c-at-s-', '-c-a-ts', 
# '-c-a-ts-', '-c-a-t-s', '-c-a-t-s-']
Ad
source: stackoverflow.com
Ad