简体   繁体   English

组合式的写法

[英]Combination of how to write an equation

I want to find all possible combination of signs of a given equation, eg Input (q,p1).我想找到给定方程的所有可能的符号组合,例如输入(q,p1)。 Output: -p1+q, p1+q, p1-q, -p1 -q.输出:-p1+q、p1+q、p1-q、-p1 -q。

Does anybody know how to do this in python?有人知道如何在python中做到这一点吗?

you can use the product function (from itertools) to create the sign combinations and concatenate them to the terms using zip and join:您可以使用 product 函数(来自 itertools)来创建符号组合并使用 zip 和 join 将它们连接到术语:

from itertools import product
terms = ["p","q1"]
opers = product(*["+-"]*len(terms))
formulas = ["".join(o+t for o,t in zip(op,terms)).strip("+") for op in opers]

print(formulas)
# ['p+q1', 'p-q1', '-p+q1', '-p-q1']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM