1

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
0

2 Answers 2

1

try for i in itertools.product(*new_list):

you need to add a * to unpack the new_list

Sign up to request clarification or add additional context in comments.

4 Comments

Wow, I can't believe that was the solution. Why is the wildcard needed there?
Your code is fine but when you pass new_list as an argument, you really are passing a list. What you want to pass are all the elements of the list. When you add an * you are unpacking the list and passing each element as a param. This is what is expected.
Look at this function: def test_func(a, b, c): # do something. If I pass a list like test_func(new_list), it will mean test_func(a = new_list). If I unpack the list like test_func(*new_list) it will mean test_func(a=new_list[0], b = new_list[1]....).
Check this out. Really useful if you know how args and kwargs work: realpython.com/python-kwargs-and-args
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.