algorithm - Generating all the combinations of two lists and output them one by one in python -
i have 2 lists
[1, 3, 4] [7, 8]
i want generate combinations of 2 list starting smallest combinations 17,18,37,38,47,48,137,138,147,148......178,378....
each combination have test it's presence in other place , if found combination present stop combination generation. example if see 17
present not generate other combinations. again if found 48
present not generate later combinations.
this pretty ugly algorithm, worked me. it's not super expensive (expect, of course, generating combinations itertools.combinations(a, i)...):
import itertools def all_combs(a): to_return = [] temp = [] in a: temp.append(i) to_return.append(temp) in range(2, len(a) + 1): temp = [] j in itertools.combinations(a, i): s = "" k in j: s = s + str(k) temp.append(int(s)) #get values 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 = [] in a_combs: j in b_combs: k in i: l in j: to_return.append(10**len(str(l)) * k + l) to_return.sort() in to_return: yield
edit: fixed bug multi-digit values weren't read in correctly edit: made function act generator edit: fixed bug involving digits (by adding sort...)
edit: here's vastly superior implementation meets generator style more closely. it's still not perfect, should provide speedup in 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 = [] in range(1, val): to_return.append([i, val-i]) return to_return def all_combs(a): to_return = {} in a: add_to_dict(to_return, len(str(i)), i) in range(2, len(a) + 1): j in itertools.combinations(a, i): s = "" k in j: s = s + str(k) add_to_dict(to_return, len(s), int(s)) #get values list permutation return to_return def all_perm(a, b): a_combs = all_combs(a) b_combs = all_combs(b) val in range(max(a_combs.keys())+max(b_combs.keys())+1): to_return = [] sums = sum_to_val(val) in sums: if not(i[0] in a_combs , i[1] in b_combs): continue j in a_combs[i[0]]: k in b_combs[i[1]]: to_return.append(10**len(str(k)) * j + k) to_return.sort() in to_return: yield
Comments
Post a Comment