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)