Python实现游戏得分计算逻辑运行结果始终为0问题排查求助
问题原因
条件判断的对象错误:map_split是拆分后得到的二维列表,结构为[['nop'], ['mul', '65'], ['sub', '20'], ['add', '75'], ['hlt']],直接判断"mul" in map_split永远返回False,所有计算分支都不会触发,得分自然始终为0。
修正方案
每次循环时取当前遍历到的单条操作指令的第一个元素作为判断依据,也可以优化循环逻辑直接遍历操作项而非索引,遇到hlt终止指令时直接跳出循环减少无效运算。
修正后代码
game_map = ['nop', 'mul 65', 'sub 20', 'add 75', 'hlt'] map_split = [item.split() for item in game_map] print(map_split) score = 0 for op_item in map_split: op = op_item[0] if op == 'hlt': break if op == "mul": score *= int(op_item[1]) elif op == "sub": score -= int(op_item[1]) elif op == "add": score += int(op_item[1]) print(score)
运行后最终输出得分为55,符合规则计算结果:初始得分0 → nop无操作 → 0*65=0 → 0-20=-20 → -20+75=55。
内容的提问来源于stack exchange,提问作者Jerry Thomas
相关产品推荐
相关产品推荐

