I'm trying to go through a string and every time I come across an asterisk (*
) replace it with every letter in the alphabet. Once that is done and another asterisk is hit, do the same again in both positions and so on. if possible saving these permutations to a .txt file or just printing them out. This is what I have and don't know where to go further than this:
alphabet = "abcdefghijklmnopqrstuvwxyz"
for i in reversed("h*l*o"):
if i =="*":
for j in ("abcdefghijklmnopqrstuvwxyz"):
Right I have some more challenges for some of the solutions below that im trying to use.
- I cannot write to a file as I just get errors.
CodePudding user response:
You can:
count
the amount of asterisks in the string.- Create the
product
of all letters with as many repetitions as given in (1). - Replace each asterisk (in order) with the matching letter:
import string
import itertools
s = "h*l*o"
num_of_asterisks = s.count('*')
for prod in itertools.product(string.ascii_lowercase, repeat=num_of_asterisks):
it = iter(prod)
new_s = ''.join(next(it) if c == '*' else c for c in s)
print(new_s)
Notes:
- Instead of creating a string of all letters, just use the
string
module. - This converts the product's tuples to iterators for easy handling of sequential replacing of each letter.
- Uses the
join
method to create the new string out of the input string. - The above code simply prints each permutation. You can of course replace it with writing to a file or anything else you desire.
CodePudding user response:
Interesting problems. I assume you mean the cartesian product and not "permutations".
I would use itertools:
string = "h*l*o"
import itertools
# for every combination of N letters
for letters in itertools.product(alphabet, repeat=string.count('*')):
# iterate over the letters
letter_iter = iter(letters)
# replace every * with the next instance
print(''.join(i if i!='*' else next(letter_iter) for i in string))