Home > Software design >  How do I get the sum of the possible combinations in this dictionary
How do I get the sum of the possible combinations in this dictionary

Time:01-28

I have a dictionary like this:

D1 = {'u1': {'a1': 2, 'a2': 3, 'a3': 1, 'a4': 2, 'a5': 0, 'a6': 0}, 'u2': {'a1': 1, 'a2': 9, 'a3': 0, 'a4': 3, 'a5': 1, 'a6': 2}, 'u3': {'a1': 0, 'a2': 0, 'a3': 0, 'a4': 0, 'a5': 0, 'a6': 9}, 'u4': {'a1': 10, 'a2': 0, 'a3': 0, 'a4': 4, 'a5': 7, 'a6': 1}}

I want to get all possible combinations of the a's, and the sum for that combination attached in this way.

e.g. If I have a permutation of 4 a's given then

{'u1': {('a1', 'a2', 'a3', 'a6'): 6.0,('a1', 'a2', 'a3', 'a4'): 8.0,('a2', 'a4', 'a5', 'a6'): 5.0,...} 'u2':{ ('a2', 'a4', 'a5', 'a6'): 15.0, ...} and so on}

I'd appreciate any explanations or ideas! thanks

Here's the present code I have, I know it's a clumsy code

final_dict = dict()
u_agroup_dict = dict()
for m, t in D1.items():
   comb = list(combinations(D1[m], 3))
      for i in comb:
        sum = 0
        for j in i:
           sum  = t[j]
        final_dict[i] = sums
      u_agroup_dict[m]  = final_dict
   print(u_agroup_dict)

CodePudding user response:

I would approach this with itertools.combinations() and a couple of for loops.

import itertools

D1 = {
    'u1': {'a1': 2, 'a2': 3, 'a3': 1, 'a4': 2, 'a5': 0, 'a6': 0},
    'u2': {'a1': 1, 'a2': 9, 'a3': 0, 'a4': 3, 'a5': 1, 'a6': 2},
    'u3': {'a1': 0, 'a2': 0, 'a3': 0, 'a4': 0, 'a5': 0, 'a6': 9},
    'u4': {'a1': 10, 'a2': 0, 'a3': 0, 'a4': 4, 'a5': 7, 'a6': 1}
}

results = {}

for key, value in D1.items():
    ## -----------------
    ## ensure we have a valid sub-dictionary for this key
    ## -----------------
    this_result = results.setdefault(key, {})
    ## -----------------

    ## -----------------
    ## iterate over the combinations of 4
    ## -----------------
    for sub_key in itertools.combinations(value.keys(), 4):
        sub_key_tuple = tuple(sub_key) ## lists can't be indexes but tuples can
        total = sum(value[t] for t in sub_key)
        this_result.setdefault(sub_key_tuple, total)
    ## -----------------

print(results)

giving:

{
    'u1': {
        ('a1', 'a2', 'a3', 'a4'): 8,
        ('a1', 'a2', 'a3', 'a5'): 6,
        ('a1', 'a2', 'a3', 'a6'): 6,
        ('a1', 'a2', 'a4', 'a5'): 7,
        ('a1', 'a2', 'a4', 'a6'): 7,
        ('a1', 'a2', 'a5', 'a6'): 5,
        ('a1', 'a3', 'a4', 'a5'): 5,
        ('a1', 'a3', 'a4', 'a6'): 5,
        ('a1', 'a3', 'a5', 'a6'): 3,
        ('a1', 'a4', 'a5', 'a6'): 4,
        ('a2', 'a3', 'a4', 'a5'): 6,
        ('a2', 'a3', 'a4', 'a6'): 6,
        ('a2', 'a3', 'a5', 'a6'): 4,
        ('a2', 'a4', 'a5', 'a6'): 5,
        ('a3', 'a4', 'a5', 'a6'): 3},
    'u2': {
        # ...
    },
    'u3': {
        # ...
    },
    'u4': {
        # ...
    }

which I hope is the result you seek.

  •  Tags:  
  • Related