Home > Back-end >  get unrepeated arrange of two dictionaries in python
get unrepeated arrange of two dictionaries in python

Time:10-27

from just two dicts(a, c), I need to find term_wMca that just gives: xA * xB * xc * W_ABC. In fact I need to leave repeated ones like W_AAC, W_BBC, just ternary ones without repeat.when bigger dicts are entered by user just ternary should be calculated in term_wMca . Is there any way to do that??

import sympy as sp
a = {'A': 1}
c = {'B': 1, 'C': 1}
term_wMca = 0
for k in a:
    for j in c:
        for l in c:
            term_wMca  = sp.symbols(f'x{str(k)}') * sp.symbols(f'x{str(j)}') * 
                sp.symbols(f'x{str(l)}') *sp.symbols(f'W_{str(l)}{str(j)}{str(k)}')
print(term_wMca)

CodePudding user response:

No need to use for-loop for each variable:

import sympy as sp
a = {'A': 1}
c = {'B': 1, 'C': 1}

keys = list(a.keys())   list(c.keys())

term_wMca = 1
for k in keys:
    term_wMca *= sp.symbols(f'x{k}')

term_wMca *= sp.symbols(f'W_'   ''.join(keys))

print(term_wMca)

Result:

W_ABC * xA * xB * xC

CodePudding user response:

Here using itertools.combination module we can avoid repeating combination as the following code make the solution to my problem, may be useful to someone else.

import sympy as sp
import itertools
a = {'A': 1}
c = {'B': 1, 'C': 1}
term_wMca = 0
term = list(sp.symbols(f'x{x}') * sp.symbols(f'x{y}') *
                sp.symbols(f'x{z}') *sp.symbols(f'W_{x}{y}{z}') for x, y in 
 itertools.combinations((c.keys()), 2) for z in (a.keys()))
for i in range(len(term)):
    term_wMca  = term[i]
print('w:', type(term_wMca), term_wMca)

it gives:

2W_BCAxAxBxC

Also, for a bigger c and a it works well: a = {'A': 1, 'M': 1, 'N': 1} c = {'B': 1, 'C': 1, 'D': 1}

W_BCAxAxBxC W_BCMxBxCxM W_BCNxBxCxN W_BDAxAxBxD W_BDMxBxDxM W_BDNxBxDxN W_CDAxAxCxD W_CDMxCxDxM W_CDNxCxD*xN

  • Related