【发布时间】:2022-12-05 17:45:44
【问题描述】:
我正在尝试进行代码第 2 天的到来,但当我尝试求和以找到剪刀石头布的总和时遇到错误:
map_input = {'A': 'Rock', 'B': 'Paper', 'C': 'Scissors', 'X': 'Rock', 'Y': 'Paper', 'Z': 'Scissors'}
points_per_shape = {'Rock': 1, 'Paper': 2, 'Scissors': 3}
points_per_outcome = {'Lose': 0, 'Draw': 3, 'Win': 6}
with open(r'C:\Users\my_name\OneDrive\Documents\advent of code\day 2\input.in') as f:
lines = f.readlines()
rounds = [entry.strip() for entry in lines]
def points_per_round(round_string):
opponent_shape = map_input[round_string[0]] #opponent, first character
our_shape = map_input[round_string[2]] #me, second character
if opponent_shape == our_shape:
return points_per_outcome['Draw'] + points_per_shape[our_shape]
elif (opponent_shape, our_shape) in [('Paper', 'Rock'), ('Rock', 'Scissors'), ('Scissors, Paper')]:
return points_per_outcome['Lose'] + points_per_shape[our_shape]
elif (opponent_shape, our_shape) in [('Rock', 'Paper'), ('Scissors', 'Rock'), ('Paper', 'Scissors')]:
return points_per_outcome['Win'] + points_per_shape[our_shape]
total = sum([points_per_round(round_string) for round_string in rounds])
print(total)
有问题的文件是这样的 B X 一个Z 是
像这样继续数千行
当我尝试运行代码时出现此错误,但如果我将最后一行从 elif 替换为 elsee,则不会出现任何错误,但会得到错误的答案
Traceback (most recent call last):
File "c:\Users\my_name\OneDrive\Documents\advent of code\day 2\rock paper scissors.py", line 23, in <module>
total = sum([points_per_round(round_string) for round_string in rounds])
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
当我尝试运行代码时出现此错误,但如果我将最后一行从 elif 替换为 elsee,则不会出现任何错误,但会得到错误的答案
【问题讨论】:
-
在某些情况下,points_per_round()是(隐含地)返回无。您需要调试该功能
-
如果您的 if/elif 案例都不适用,您的程序将返回 None(NoneType 的实例)。 sum() 使用 + 运算符,它不能将 None 添加到数字。如果所有情况都不适用,您需要指定要做什么。例如,添加
else: return 0
标签: python