gpt4 book ai didi

python - 如何在添加 "coefficient"时合并列表中的重复元素?

转载 作者:行者123 更新时间:2023-11-28 22:14:09 27 4
gpt4 key购买 nike

我正在编写一个“简化”函数来简化多项式,以便 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)

因为所有项目都按其原始顺序处理,并且使用列表附加而不是哈希表(如 setdict),所以顺序得以保留。

关于python - 如何在添加 "coefficient"时合并列表中的重复元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53543048/

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