Skip to content Skip to sidebar Skip to footer

Generating All The Combinations Of Two Lists And Output Them One By One In Python

I have two lists [1, 3, 4] [7, 8] I want to generate all the combinations of two list starting from the smallest combinations like 17,18,37,38,47,48,137,138,147,148......178,378..

Solution 1:

This is a pretty ugly algorithm, but it worked for me. It's also not super expensive (expect, of course, for generating all the combinations with itertools.combinations(a, i)...):

import itertools

def all_combs(a):
    to_return = []
    temp = []
    for i in a:
        temp.append(i)
    to_return.append(temp)
    for i in range(2, len(a) + 1):
        temp = []
        for j in itertools.combinations(a, i):
            s = ""
            for k in j:
                s = s + str(k)
            temp.append(int(s)) #Get all values from the list permutation
        to_return.append(temp)
    print(to_return)
    return to_return

def all_perm(a, b):
    a_combs = all_combs(a)
    b_combs = all_combs(b)
    to_return = []
    for i in a_combs:
        for j in b_combs:
            for k in i:
                for l in j:
                    to_return.append(10**len(str(l)) * k + l)
    to_return.sort()
    for i in to_return:
        yield i

EDIT: Fixed a bug where multi-digit values weren't read in correctly EDIT: Made the function act as a generator EDIT: Fixed a bug involving digits (by adding a sort...)

EDIT: Here's a vastly superior implementation which meets the generator style much more closely. It's still not perfect, but it should provide good speedup in the average case:

import itertools

def add_to_dict(dict, length, num):
    if not length in dict:
        dict[length] = []
    dict[length].append(num)

def sum_to_val(val):
    to_return = []
    for i in range(1, val):
        to_return.append([i, val-i])
    return to_return

def all_combs(a):
    to_return = {}
    for i in a:
        add_to_dict(to_return, len(str(i)), i)
    for i in range(2, len(a) + 1):
        for j in itertools.combinations(a, i):
            s = ""
            for k in j:
                s = s + str(k)
            add_to_dict(to_return, len(s), int(s)) #Get all values from the list permutation
    return to_return

def all_perm(a, b):
    a_combs = all_combs(a)
    b_combs = all_combs(b)
    for val in range(max(a_combs.keys())+max(b_combs.keys())+1):
        to_return = []
        sums = sum_to_val(val)
        for i in sums:
            if not(i[0] in a_combs and i[1] in b_combs):
                continue
            for j in a_combs[i[0]]:
                for k in b_combs[i[1]]:
                    to_return.append(10**len(str(k)) * j + k)
        to_return.sort()
        for i in to_return:
            yield i

Post a Comment for "Generating All The Combinations Of Two Lists And Output Them One By One In Python"