Home > Enterprise >  Sort a sum of products in sympy output
Sort a sum of products in sympy output

Time:11-05

I try to find a pattern using simpy.

import numpy as np
import sympy
from sympy import *
from sympy import simplify

b = symbols('b:100')
a = symbols('a:100')


A = Matrix([[1, 0],[0, 1]])
for i in [10,9,8]:
        A = A @ Matrix([[1 b[i]-a[i] , -b[i]],[1, 0]])

print(expand(simplify(A[0,0])))

The output is

-a10*a8*a9   a10*a8*b9   a10*a8   a10*a9*b8   a10*a9 - a10*b8*b9 - a10*b8 - a10   a8*a9*b10   a8*a9 - a8*b10*b9 - a8*b9 - a8 - a9*b10*b8 - a9*b10 - a9*b8 - a9   b10*b8*b9   b8*b9   b8   1

Is there any way to sort the summands in a more usefull way? Like show first all summands with containing 3 characters and then summands with only 2 ... and also sort the products in the summands so that a comes before b and a10 before a9 before a8 and so on?

theres a command "sorted" in the simpy bib but i need list elements for this command. Any other nice suggestions to solve this problem?

CodePudding user response:

You can make your own key when sorting. Does this do what you want?

enter image description here

  • Related