一切完成后,我得到关键错误:“ po5”

时间:2019-08-19 09:05:06

标签: python-3.x dictionary for-loop if-statement while-loop

month_txt.setText(Html.fromHtml("$0.99" + "<b>" + "/Month" + "</b>"));

即使我得到了想要的car={"po1":50,"po2":"-","po3":15,"po4":"+","po5":12} vocar = list(car.keys()) inter=0 def cal(car,vocar,inter): while len(car)!=1: for inter in range(len(car)): if car.get(vocar[inter],0)=="+": new=car.get(vocar[inter-1])+car.get(vocar[inter+1]) car.pop(vocar[inter]) car.pop(vocar[inter+1]) car.update({vocar[inter-1]:new}) car1=car vocar1=list(car1.keys()) inter1=0 cal(car1,vocar1,inter1) elif car.get(vocar[inter],0)=="-": new=car.get(vocar[inter-1])-car.get(vocar[inter+1]) car.pop(vocar[inter]) car.pop(vocar[inter+1]) car.update({vocar[inter-1]:new}) car1=car vocar1=list(car1.keys()) inter1=0 cal(car1,vocar1,inter1) print(car) cal(car,vocar,inter) ,我仍然遇到关键错误。

但是在完成所有操作后,它给了我一个关键错误。请帮忙!

1 个答案:

答案 0 :(得分:0)

  • 起初:
while len(car)!=1

您从汽车上弹出物品并尝试制作recursion function,然后可以使用:

    if not car:
        return
    for inter in range(len(car)):
        # ....
  • 当您像这样制作loop时:
for inter in range(len(car))

这意味着:

| loop | inter |
|:----:|:-----:|
|   1  |   0   | car => [X, X, X ,X ,X]
|   2  |   1   | car => [X, X, X ,X]
|   3  |   2   | car => [X, X, X]  ! ERR !
|   4  |   3   | 
|   5  |   4   | 

loop 3中,您遇到错误(也许;))

您可以使用主要的dict

for inter in car:
  • 根据以上内容,您不再需要vocar
if car.get(inter,0)=="+":
  • “ po1”为str,“ po2”为int,则您不能在+int之间使用int运算符。

  • 字典是无序的

    这意味着,每次您运行它时,项目安排可能会更改!所以我改变了:

car = [("po1",50), ("po2","-"),("po3",15),("po4","+"),("po5",12)]
  • 我们更改了car,然后我们可以这样做:
        if inter[1] == "+":
            car[head-1] = (inter[0], car[head-1][1]+car[head+1][1])
  • 最后,我们必须首先删除car[head+1],然后再删除car[inter]
car = [("po1",50), ("po2","-"),("po3",15),("po4","+"),("po5",12)]

def cal(car):
    head = 0
    if not car:
        return
    for inter in car:
        if inter[1] == "+":
            car[head-1] = (inter[0], car[head-1][1]+car[head+1][1])
            car.remove(car[head+1])
            car.remove(inter)
            cal(car)
        elif inter[1] =="-":
            car[head-1] = (inter[0], car[head-1][1]-car[head+1][1])
            car.remove(car[head+1])
            car.remove(inter)
            cal(car)
        head += 1
    return car[0][1]

print(cal(car))

OUT:
===
47