原题是一个棒球积分的问题,就不详细描述了https://leetcode.com/problems/baseball-game/description/
刚开始写的代码如下:
class Solution:
def calPoints(self, ops):
"""
:type ops: List[str]
:rtype: int
"""
n=len(ops)
res = []
res = [[0,0]]*n #刚开始是这样定义的二维列表,想法是第一位保存对应回合的得分数,
#第二位保存该回合得分是否有效,1代表有效,0代表无效
'''for i in range(n): #把上面对res的定义改成这样就可以正常运行了
res.append([0,0])'''
for i in range(n):
if ops[i]=='C':
j = i-1
while (not res[j][1]):
j -= 1
res[j][1] = 0
elif ops[i] == 'D':
j = i-1
while not res[j][1] :
j -= 1
res[i][0] += res[j][0]*2
res[i][1] = 1
elif ops[i] == '+':
j = i-1
while not res[j][1]:
j -= 1
res[i][0] += res[j][0]
k = j-1
while not res[k][1]:
k -= 1
res[i][0] += res[k][0]
res[i][1] = 1
else:
res[i][0] = int(ops[i])
res[i][1] = 1
print(res) #结果一直有问题,所以就在此打印一下res列表看一下
sum =0
for i in res:
if i[1]:
sum +=i[0]
return sum
这个题的报错关键问题出在了列表定义上,试了一下如下:
>> list1 = [[1,2]]*3
>>> list1
[[1, 2], [1, 2], [1, 2]]
>>> list[0][1] = 0
>>> list1[0][1] = 0
>>> list1
[[1, 0], [1, 0], [1, 0]]
>>>
第一种情况:
>>> m = [1,2,[3,4,5]]
>>> n=m
>>> m[0]=-1
>>> m[2][0] = -1
>>> n
[-1, 2, [-1, 4, 5]]
第二种情况:
>>> m = [1,2,[3,4,5]]
>>> n=m.copy()
>>> m[0]=-1
>>> m[2][0] = -1
>>> n
[1, 2, [-1, 4, 5]]
>>> m
[-1, 2, [-1, 4, 5]]
第三种情况:
>>> from copy import deepcopy
>>> m = [1,2,[3,4,5]]
>>> n=deepcopy(m)
>>> m[0] = -1
>>> m[2][0] = -1
>>> m
[-1, 2, [-1, 4, 5]]
>>> n
[1, 2, [3, 4, 5]]