import itertools
alphabet = {
"A": 1,
"B": 2,
"C": 3,
"D": 4,
"E": 5,
"F": 6,
"G": 7,
"H": 8,
"I": 9,
"J": 10,
"K": 11,
"L": 12,
"M": 13,
"N": 14,
"O": 15,
"P": 16,
"Q": 17,
"R": 18,
"S": 19,
"T": 20,
"U": 21,
"V": 22,
"W": 23,
"X": 24,
"Y": 25,
"Z": 26
}
def gen_combination_values(n):
comb_values = {}
for i in range(n + 1):
for product in itertools.product(alphabet.keys(), repeat=i):
prod = list(product)
prod.sort()
value = 0
comb = ""
for char in prod:
value += alphabet[char]
comb += char
try:
comb_values[value].add(comb)
except KeyError:
comb_values[value] = set()
comb_values[value].add(comb)
print(comb_values)
return comb_values
I have this script and I would like to use only a part of the permutation how to do it?
I want the next part of the script to use only all results up to 10
{0: {''}, 1: {'A'}, 2: {'B', 'AA'}, 3: {'C', 'AB', 'BA'}, 4: {'BB' , 'AC', 'D', 'CA'}, 5: {'AD', 'BC', 'E', 'CB', 'DA'}, 6: {'F', 'CC', ' AE ',' DB ',' BD ',' EA '}, 7: {' CD ',' AF ',' G ',' EB ',' FA ',' BE ',' DC '}, 8: {'AG', 'CE', 'EC', 'H', 'BF', 'FB', 'DD', 'GA'}, 9: {'AH', 'DE', 'HA', ' BG ',' CF ',' ED ',' I ',' GB ',' FC '}, 10: {' EE ',' HB ',' DF ',' FD ',' IA ',' AI ' , 'J', 'BH', 'CG', 'GC'},
and the rest not to use
11: {'FE', 'BI', 'CH', 'AJ', 'JA', 'DG', 'GD', 'IB', 'HC', 'EF'}, 12: {'EG' , 'CI', 'IC', 'BJ', 'FF', 'DH', 'HD', 'JB', 'GE'}, 13: {'EH', 'HE', 'DI', ' CJ ',' FG ',' JC ',' ID ',' GF '}, 14: {' DJ ',' EI ',' IE ',' HF ',' JD ',' GG ',' FH ' }, 15: {'EJ', 'IF', 'GH', 'JE', 'FI', 'HG'}, 16: {'IG', 'JF', 'FJ', 'GI', ' HH '}, 17: {' JG ',' GJ ',' HI ',' IH '}, 18: {' JH ',' II ',' HJ '}, 19: {' IJ ',' JI ' }, 20: {'JJ'}}
how to achieve this? Basically here's the whole code I don't know what to do with all the attempts failed
I'm looking for only the first ten premutations to be used from the code
I suggest a re-write of your gen_combination_values() function. There are less cumbersome ways to build your dictionary (which I show in this code). You then need to construct a new dictionary to return which is based on your limit (which defaults to 10).
import itertools
ALPHABET = {k:i for i, k in enumerate('ABCDEFGHIJ', 1)}
def gen_combination_values(n, limit=10):
comb_values = {}
for i in range(n + 1):
for product in itertools.product(ALPHABET, repeat=i):
value = sum(ALPHABET[c] for c in product)
comb = ''.join(c for c in product)
comb_values.setdefault(value, set()).add(comb)
return {k:v for k, v in comb_values.items() if k <= limit}
print(gen_combination_values(2))
Output:
{0: {''}, 1: {'A'}, 2: {'B', 'AA'}, 3: {'C', 'BA', 'AB'}, 4: {'D', 'AC', 'BB', 'CA'}, 5: {'DA', 'E', 'AD', 'BC', 'CB'}, 6: {'CC', 'AE', 'EA', 'BD', 'DB', 'F'}, 7: {'AF', 'FA', 'CD', 'BE', 'G', 'EB', 'DC'}, 8: {'AG', 'GA', 'CE', 'EC', 'FB', 'DD', 'H', 'BF'}, 9: {'CF', 'FC', 'AH', 'BG', 'ED', 'DE', 'GB', 'HA', 'I'}, 10: {'DF', 'EE', 'BH', 'IA', 'CG', 'AI', 'HB', 'GC', 'J', 'FD'}}