Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating all combinations and permutations of each word in a list

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()
like image 375
Kinara Nyakaru Avatar asked Mar 04 '23 08:03

Kinara Nyakaru


2 Answers

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()
like image 138
abhilb Avatar answered Apr 24 '23 04:04

abhilb


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/

like image 26
phylogram Avatar answered Apr 24 '23 04:04

phylogram