0

I'm trying to replace a character in a string with all possible combinations of "ABCDEF", and create a file with all combinations.

I have the first part working but can't get it to append to the list and then write to the file.

I'd appreciate any help you can give.

import itertools

keyList = []

def replaceX(s, chars):
    for element in map(iter, itertools.product(chars, repeat=s.count("X"))):
        yield ''.join(char if char != 'X' else next(element) for char in s)
        keyList.append(*replaceX("ABCXXABXXABCDEF\n", "ABCDEF"))

# print(*replaceX("ABCXXABXXABCDEF\n", "ABCDEF"))

print(keyList)

outFile = open("key-file.txt", "w")
outFile.writelines(keyList)
outFile.close()
Andy
  • 7
  • 7
  • 1
    Why are you recursing in the `replaceX` function? What behaviour are you seeing? – doctorlove Dec 02 '21 at 10:14
  • 2
    Just remove the `keyList.append` line and call as `keyList = list(replaceX("ABCXXABXXABCDEF\n", "ABCDEF"))` or better yet - don't create a list at all: `for comb in replaceX("ABCXXABXXABCDEF\n", "ABCDEF"): outfile.write(comb)` – Tomerikoo Dec 02 '21 at 10:16
  • @doctorlove Removing `keyList.append(*replaceX("ABCXXABXXABCDEF\n", "ABCDEF"))` and using `print(*replaceX("ABCXXABXXABCDEF\n", "ABCDEF"))` gives me all the combinations. I'm just then trying to append all the combinations to a list and write that to a file. – Andy Dec 02 '21 at 10:20
  • Why do you need a list? If you just want to write to the file iterate over the generator and write each element to the file. No need to use a redundant middle-step list – Tomerikoo Dec 02 '21 at 10:22
  • Ya, good point. I guess I was doing the list so I could print it but as you say I don't need it. – Andy Dec 02 '21 at 10:24
  • 1
    Anyway, as I said before, if you ***really*** need a list, you can just do `list(replaceX("ABCXXABXXABCDEF\n", "ABCDEF")` (after removing the `append` line...) – Tomerikoo Dec 02 '21 at 10:25
  • Does this answer your question? [Convert generator object to list for debugging](https://stackoverflow.com/questions/24130745/convert-generator-object-to-list-for-debugging) – Tomerikoo Dec 02 '21 at 10:27

0 Answers0