我正在编写一个函数“simplify”来简化多项式,以便 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
,但这会改变顺序。
最好的方法是什么?谢谢。
最佳答案
使用 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
),因此顺序被保留。
关于python - 如何在添加 "coefficient"的同时合并列表中的重复元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53543048/