gpt4 book ai didi

python - 没有对齐 Sympy 的漂亮 split

转载 作者:太空狗 更新时间:2023-10-29 17:34:47 27 4
gpt4 key购买 nike

我正在尝试使用 Sympy 很好地打印一些分区,但我注意到它没有显示对齐。

import sympy
sympy.init_printing(use_unicode=True)

sympy.pprint(sympy.Mul(-1, sympy.Pow(-5, -1, evaluate=False), evaluate=False))
# Output:
# -1
# ───
# -5 # Note that "-5" is displayed slightly more on the right than "-1".

原因/修复方法?

编辑: 我使用 inspect.getsourceinspect.getsourcefile 做了很多逆向工程,但并没有真正帮助最后。

Sympy 中的 Pretty Printing 似乎依赖于 Jurjen Bos 的 Prettyprinter

import sympy

from sympy.printing.pretty.stringpict import *

sympy.init_printing(use_unicode=True)

prettyForm("-1")/prettyForm("-5")
# Displays:
# -1
# --
# -5

所以它确实显示对齐,但我无法让它使用 unicode。

PrettyPrinter 是从文件 sympy/printing/pretty/pretty.py 的方法 PrettyPrinter._print_Mul 中调用的,它只是 返回 prettyForm.__mul__(* a)/prettyForm.__mul__(*b) 我认为 ab 只是 ['-1']['-5'] 但它不起作用。

最佳答案

找出奇怪部分的来源:

stringpict.py 第 417 行:

        if num.binding==prettyForm.NEG:
num = num.right(" ")[0]

这仅针对分子进行。如果分子为负数,它会在分子后添加一个空格……很奇怪!

除了直接编辑文件之外,我不确定是否可以修复。我将在 Github 上报告此事。

感谢大家的帮助和建议。

PS:最后,我使用 pdb 帮助我调试并弄清楚到底发生了什么!

编辑:如果您不能/不想编辑代码源,请修复:

import sympy
sympy.init_printing(use_unicode=True)

from sympy.printing.pretty.stringpict import prettyForm, stringPict

def newDiv(self, den, slashed=False):
if slashed:
raise NotImplementedError("Can't do slashed fraction yet")
num = self
if num.binding == prettyForm.DIV:
num = stringPict(*num.parens())
if den.binding == prettyForm.DIV:
den = stringPict(*den.parens())

return prettyForm(binding=prettyForm.DIV, *stringPict.stack(
num,
stringPict.LINE,
den))

prettyForm.__div__ = newDiv

sympy.pprint(sympy.Mul(-1, sympy.Pow(-5, -1, evaluate=False), evaluate=False))

# Displays properly:
# -1
# ──
# -5

我只是从代码源中复制了函数并删除了有罪的行。

可能的改进可能是 functools.wraps 新功能与原始功能。

关于python - 没有对齐 Sympy 的漂亮 split ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30197808/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com