[Python] Turning off constructor addition reordering b+a => a+b

Discussão em 'Python' iniciado por Stack, Agosto 2, 2025.

  1. Stack

    Stack Membro Participativo

    In Sympy, I'm trying to get some symbolic expressions to look exactly like my source material, but it appears that constructors do some rearrangements, most simply Add:

    >>> a, b = symbols("a b")
    >>> b+a
    a + b
    >>> srepr(b+a)
    Add(Symbol('a'), Symbol('b'))


    Obviously this is a good idea most of the time, but I'm trying to show my expressions to be exactly right before doing any change, however obvious.

    The help for Add says:


    Add() evaluates the argument unless evaluate=False is passed. The evaluation logic includes:

    1. Flattening ...
    2. Identity removing ...
    3. Coefficient collecting ...
    4. Term sorting
      Add(y, x, 2) -> Add(2, x, y)
    ​

    But it seems not to work:

    >>> srepr(Add(b, a, evaluate=False))
    Add(Symbol('a'), Symbol('b'))


    Is this possible? Have I missed something?

    What I'm actually wanting to make is this:


    ⎛ 1 ⎞
    ⎜─────────────────⎟
    ⎜ 1 1 ⎟
    ⎜─────── + ───────⎟
    ⎜R⋅N + S 1 ⎟
    ⎜ E + ───⎟
    ⎝ s⋅C⎠
    ─────────────────────────────
    ⎛ 1 ⎞
    ⎜D + L⋅s + ─────────────────⎟
    ⎜ 1 1 ⎟
    ⎜ ─────── + ───────⎟
    ⎜ R⋅N + S 1 ⎟
    ⎜ E + ───⎟
    ⎝ s⋅C⎠


    But the expression reordering produces the following.

    1
    ─────────────────────────────────────────────────
    ⎛ 1 1 ⎞ ⎛ 1 ⎞
    ⎜─────── + ───────⎟⋅⎜D + L⋅s + ─────────────────⎟
    ⎜N⋅R + S 1 ⎟ ⎜ 1 1 ⎟
    ⎜ E + ───⎟ ⎜ ─────── + ───────⎟
    ⎝ C⋅s⎠ ⎜ N⋅R + S 1 ⎟
    ⎜ E + ───⎟
    ⎝ C⋅s⎠

    • Sympy 1.14.0
    • Python 3.10.12
    • Ubuntu 22.04.4 LTS

    Continue reading...

Compartilhe esta Página