0

I want to write a code which gives me all the possible combinations of n elements in a k length k>n.The issue with this code is that i run out of memory quite fast.I was wondering if someone knew how to fix this with generators.I don't want to get all the possible combinations of a list elements. I want to get all the combinations of the elements in a certain length. Thanks.

def allstrings(alphabet, length):
    """Find the list of all strings of 'alphabet' of length 'length'"""

    if length == 0: return []

    c = [[a] for a in alphabet[:]]
    if length == 1: return c

    c = [[x,y] for x in alphabet for y in alphabet]
    if length == 2: return c

    for l in range(2, length):
        c = [[x]+y for x in alphabet for y in c]

    return c

if __name__ == "__main__":
    for p in allstrings(['a','b','c'],4):
        print (p)
  • 2
    Have you looked in [`itertools`](https://docs.python.org/3/library/itertools.html)? I'm assuming you're doing this as a learning exercise, not because you actually need all the combinations of those three letters—but notice that `combinations`, `product`, etc. all come with "roughly equivalent" code that you can read to see how to do it yourself. – abarnert Jul 08 '18 at 00:34
  • It was an example, i need the combinations of 64 elements in a length of 10000 approximately but i get Memoryerror. Thanks anyway! – Rick Deckard Jul 08 '18 at 00:43
  • "i need the combinations of 64 elements in a length of 10000" - no you don't, you need to figure out a better way to solve whatever problem you wanted to use that output for. You're never going to finish going through all that output even if you dodge the memory problems. – user2357112 Jul 08 '18 at 00:58

1 Answers1

2
import itertools

itertools.combinations('alphabet', length)

From How to get all possible combinations of a list’s elements?

nad_rom
  • 419
  • 4
  • 9