Reputation: 13
I'm trying to print all of the possible character substitutions for the word "otaku".
#!/usr/bin/python3
import itertools
user_input = "otaku"
dict = {
'c': ['c', 'C'],
'a': ['a', 'A', '@'],
't': ['t', 'T'],
'k': ['k', 'K'],
'u': ['u', 'U'],
'e': ['e', 'E', '3'],
'o': ['o', 'O', '0']
}
output = ""
for i in itertools.product(dict['o'],dict['t'],dict['a'],dict['k'],dict['u']):
output += ''.join(i) + "\n"
print(output)
The above script works but I need the itertools.product()
input (dict['o'],dict['t'],dict['a'],dict['k'],dict['u']
) to be dynamic (e.g., new_list
):
#!/usr/bin/python3
import itertools
user_input = "otaku"
dict = {
'c': ['c', 'C'],
'a': ['a', 'A', '@'],
't': ['t', 'T'],
'k': ['k', 'K'],
'u': ['u', 'U'],
'e': ['e', 'E', '3'],
'o': ['o', 'O', '0']
}
new_list = []
for i in user_input:
new_list.append(dict[i])
output = ""
for i in itertools.product(new_list):
output += ''.join(i) + "\n"
print(output)
This errors with:
TypeError: sequence item 0: expected str instance, list found
I tried the solutions found here, but converting the list to a str breaks the itertools.product line.
How can I pass dynamic input into itertools.product()
?
Desired output:
otaku
otakU
otaKu
otaKU
otAku
otAkU
otAKu
otAKU
ot@ku
ot@kU
ot@Ku
ot@KU
oTaku
oTakU
oTaKu
oTaKU
oTAku
oTAkU
oTAKu
oTAKU
oT@ku
oT@kU
oT@Ku
oT@KU
Otaku
OtakU
OtaKu
OtaKU
Ot@KU
Upvotes: 1
Views: 3383
Reputation: 349
you can use *
to unpack it:
for i in itertools.product(*new_list)
you can also do it by list comprehension
c = ["".join(x) for x in itertools.product(*new_list)]
for i in c:
print(i)
Upvotes: 1
Reputation: 438
try for i in itertools.product(*new_list):
you need to add a *
to unpack the new_list
Upvotes: 1