1
    temp1 = []
    filtered_tokens = ['once','upon','a','time','in','the','forest']
    for i in range(len(filtered_tokens)):
        for j in range(i+1,len(filtered_tokens)):
            temp1.append(filtered_tokens[i]+' '+filtered_tokens[j])

filetered_list, in the above code contains 10,000 words, i only gave the sample list.

output needed for me: once upon, once a, once in, once the, once forest, upon a, upon time, upon in, upon the, upon forest, a time, a in, a the, a forest, time in, time the, time forest, in the, in forest, the forest

when i wrote the logic and run it, compiler thrown me Low memory exception at run time.

Please help me how i can solve this using Combinations or any other python language.

Thank You

SBN AB
  • 161
  • 1
  • 1
  • 17
  • If your list contains about 10,000 words, the number of combinations will be about 50,000,000. So, you should consider what you want to do with that many combinations. Anyway, storing the whole list in memory is probably not a good idea. You could use a generator, see `itertools.combinations`. – Thierry Lathuille Aug 02 '17 at 09:35

1 Answers1

7

For combinations you can use the itertools module.

import itertools
temp1 = itertools.combinations(filtered_tokens, 2)

will create all combinations of 2 words. If you want the list just convert the generator:

temp1 = list(temp1)
tupui
  • 5,738
  • 3
  • 31
  • 52
  • But, result returned by the .combinations is **Object**, when i tried storing by iterating those object, i again encountered **memory exception** – SBN AB Aug 02 '17 at 09:47
  • @SBNAB the function returns a generator object. As I explained, you can convert it into a list. As commented by Thierry, all this listing may not fit into memory. Thus, you can use the generator object to solve this. – tupui Aug 02 '17 at 09:48
  • yeah! i did the same, it is throwing memory exception – SBN AB Aug 02 '17 at 09:50
  • @SBNAB yes because the list is to big. So try to work with the generator instead. See: https://stackoverflow.com/a/1756156/6522112 for examples. – tupui Aug 02 '17 at 09:51