我在encodebat上尝试这个小问题列表。这是问题的链接:http://codingbat.com/prob/p108886 我必须计算列表的总和,除了忽略一个以6开头并以7结尾的子列表。我正在分享我写的代码,任何人都可以帮我解决我犯错误的地方。
def sum67(nums):
def c6(six):
if len(six) > 0:
if 6 not in six:
return six
else:
count= 0
for a in six:
if a== 6:
count = count + 1
for b in range(count):
in1= six.index(6)
in2= six.index(7)
six= six[0:in1]+six[in2+1:]
return six
else:
return 0
a= c6(nums)
return sum(nums)
答案 0 :(得分:0)
Here I found the error for the list = [6,6,1, 2, 2, 6, 99, 99, 7]
I have written the same code in tests.py and run with some examples.
I also found that sum(nums)
needs to be changed to sum(a)
def sum67(nums):
def c6(six):
if len(six) > 0:
if 6 not in six:
return six
else:
count = 0
for a in six:
if a == 6:
count = count + 1
for b in range(count):
in1 = six.index(6)
in2 = six.index(7)
six = six[0:in1] + six[in2 + 1:]
return six
else:
return 0
a = c6(nums)
return sum(a)
numbers = [6,6,1, 2, 2, 6, 99, 99, 7]
sum1 = sum67(numbers)
Traceback (most recent call last):
File "tests.py", line 26, in <module>
sum1 = sum67(numbers)
File "tests.py", line 21, in sum67
a = c6(nums)
File "tests.py", line 13, in c6
in1 = six.index(6)
ValueError: 6 is not in list
Let me know if I am wrong.
I tried below code in my console. It's working for me all my inputs.
def sum67(nums):
def c6(six):
if len(six) > 0:
if 6 not in six:
return six
else:
count = 0
for a in six:
if a == 6:
count = count + 1
for b in range(count):
if six and six.__contains__(6) and six.__contains__(7):
in1 = six.index(6)
in2 = six.index(7)
six = six[0:in1] + six[in2 + 1:]
return six
else:
return 0
a = c6(nums)
return sum(a)
numbers = [6, 6, 1, 2, 2, 6, 99, 99, 7, 1, 2, 6, 1, 2, 7, 1, 2,6,7]
sum1 = sum67(numbers)
print("Sum value = %s" % sum1)
Sum value = 6
But I am getting below error in the URL( http://codingbat.com/prob/p108886)
Line 12: __contains__ is an invalid attribute name because it starts with "_".
所以我不知道这个错误的原因。
答案 1 :(得分:0)
您看到的错误消息实际上不是编译器错误。它是index
在未找到参数时引发的异常值:
>>> [1,2,3].index(6)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 6 is not in list
你需要抓住错误并做出适当的回应:
try:
in1 = six.index(6)
except ValueError:
# What should you do if there is no 6 in the list?
# Do it here.