我正在编写一个函数“简化”来简化多项式,这样simplify("2xy-yx")可以返回"xy",simplify("-a+5ab+3a-c-2a")可以返回"-c+5ab"等等。
我所处的阶段是,我把多项式分解成多个多项式,作为一个列表的元素,并将单调词的系数和字母(变量)部分分开。
例如
input = '3xy+y-2x+2xy'我的过程给了我:
Var = ['xy', 'y', 'x', 'xy']
Coe = ['+3', '+1', '-2', '+2']我想要做的是合并相同的单调词,并将它们相应的系数同时加在另一个列表中。
我的代码是:
Play1 = Letter[:]
Play2 = Coe[:]
for i in range(len(Play1) - 1):
for j in range(i+1, len(Play1)):
if Play1[i] == Play1[j]:
Letter.pop(j)
Coe[i] = str(int(Play2[i]) + int(Play2[j]))
Coe.pop(j)但是,这似乎只适用于每个重复元素显示不超过两次的列表。例如,输入"-a+5ab+3a-c-2a“给我:
IndexError: pop index out of range我想使用set,但这会改变顺序。
最好的方法是什么?谢谢。
发布于 2018-11-29 16:06:44
为了便于处理,将列表与zip()组合起来,并创建一个新列表:
newVar = []
newCoe = []
for va, co in zip(Var, Coe):
# try/except (EAFP) is very Pythonic
try:
# See if this var is seen
ind = newVar.index(va)
# Yeah, seen, let's add the coefficient
newCoe[ind] = str(int(newCoe[ind]) + int(co))
except ValueError:
# No it's not seen, add both to the new lists
newVar.append(va)
newCoe.append(co)因为所有项目都是按其原始顺序处理的,并且使用列表附加而不是哈希表(如set和dict),所以顺序将保持不变。
发布于 2018-11-29 16:11:29
这是一种典型的用例,在这种用例中,dict会派上用场:
from collections import defaultdict
Var = ['xy', 'y', 'x', 'xy']
Coe = ['+3', '+1', '-2', '+2']
polynom = defaultdict(int)
for var, coeff in zip(Var, Coe):
polynom[var] += int(coeff)
Var, Coe = list(polynom.keys()), list(polynom.values())发布于 2018-11-30 06:53:06
尝试如下:和使用regex
import re
# a = '3xy+y-2x+2xy'
a = "-a+5ab+3a-c-2a"
i = re.findall(r"[\w]+", a)
j = re.findall(r"[\W]+", a)
if len(i)!=len(j):
j.insert(0,'+')
d = []
e = []
for k in i:
match = re.match(r"([0-9]+)([a-z]+)", k, re.I)
if match:
items = match.groups()
d.append(items[0])
e.append(items[1])
else:
d.append('1')
e.append(k)
print(e)
f = []
for ii,jj in zip(j,d):
f.append(ii+jj)
print(f)输入:
a = "-a+5ab+3a-c-2a"输出:
['a', 'ab', 'a', 'c', 'a']
['-1', '+5', '+3', '-1', '-2']输入:
a = '3xy+y-2x+2xy'输出:
['xy', 'y', 'x', 'xy']
['+3', '+1', '-2', '+2']https://stackoverflow.com/questions/53543048
复制相似问题