Given a list of input words, write a program that can generate all the words that can be formed using a subset of characters from each input word.
For example, if the list of input words is: cat mat
The output file will look like: a c t at ta act cat
I am new to pythonic code. I have code that is already running but it does not work for very long words like 'photosynthesis'. What could I be missing?
from itertools import permutations
def x():
y = ["cat", "mat"]
for i in y:
z = [perm for length in range(1, len(i) + 1) for perm in permutations(i, length)]
for i in z:
a = ''.join(i)
print(a)
x()
Its just taking lot of time to compute the results for all the permutations of "photosynthesis". Use generator based approach as shown below.
from itertools import permutations
def get_perms(value, length):
for l in range(length):
for perm in permutations(value, l):
yield ''.join(perm)
else:
return []
def x():
y = ["photosynthesis"]
for i in y:
perms = get_perms(i, len(i))
for item in perms:
print(item)
x()
Most probably, you are running out of memory. But in this case, there is no need for this. Instead of an an list comprehension, you need an generator. For example
from itertools import permutations
def x(y):
for i in y:
for length in range(1, len(i) + 1):
for perm in permutations(i, length):
yield ''.join(perm)
for p in x(["cat", "mat"]):
print(p)
and now you can also write all this to a file – line by line – or a database, or whatever.
The reason is, that the generator does not keep the whole data in memory. It prints it / writes it to a file and forgets it. And permutations tend to get very big quick.
(You can also use generator comprehensions)
https://code-maven.com/list-comprehension-vs-generator-expression https://www.geeksforgeeks.org/python-list-comprehensions-vs-generator-expressions/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With