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?
CodePudding user response:
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-']
CodePudding user response:
word = input("Enter the word: ")
def insert_into_str(s, index, in_str):
arr = list(s)
arr.insert(index, in_str)
return "".join(arr)
permutations = []
for i in range(len(word) 1):
permutations.append(insert_into_str(word, i, "-"))
print(permutations)
>>> Enter the word: cats
>>> ['-cats', 'c-ats', 'ca-ts', 'cat-s', 'cats-']
CodePudding user response:
Here is a way that does not use itertools. Interpret a binary string as where to place hyphens
def add_hyphens(str):
hyphen_words=[]
a=2**len(str)
b=2**(len(str) 1)
for i in range(a,b,1):
str1=bin(i) #a string 0b1<0's and 1's>
str2=str1[3:] #take off the 0b and the first '1'
tmp_s=""
for j,char1 in enumerate(str):
if str2[j] == '1':
tmp_s =tmp_s '-'
tmp_s = tmp_s char1
hyphen_words.append(tmp_s)
hyphen_words.append(tmp_s '-')
return hyphen_words
print(add_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-']