我无法弄清楚为什么我的代码不起作用。问题是:
返回数组中数字的总和,为空数组返回0。除了数字13是非常不吉利的,所以它不计算在13之后立即出现的数字也不计算。
sum13([1,2,2,1])→6
sum13([1,1])→2
sum13([1,2,2,1,13])→6
我的回答:
def sum13(nums):
count = sum(nums)
for i in range(len(nums)):
if nums[i] == 13:
count = count - 13
count = count - nums[i+1]
return count
答案 0 :(得分:1)
def sum13(nums):
count = 0
if nums == []: return count
if nums[0] != 13:
count += nums[0]
for i in range(1,len(nums)):
if nums[i] != 13 and nums[i-1] != 13:
count += nums[i]
return count
答案 1 :(得分:0)
删除有问题的元素,然后总结剩下的内容。使用生成器使这非常简单
def remove_13(l):
it = iter(l)
for x in it:
if x == 13:
try:
next(it)
except StopIteration:
return
else:
yield x
def sum13(l):
return sum(remove_13(l))
答案 2 :(得分:0)
def sum13(nums):
count = sum(nums)
for i in range(len(nums)):
if nums[i] == 13:
# count = count - 13
# count = count - nums[i+1]
#print(nums[:i])
count = sum(nums[:i])
return count
答案 3 :(得分:0)
def sum13(nums):
if 13 in nums:
try:
nums.append(0)
for i in range(len(nums)):
if nums[i] == 13:
nums.remove(nums[i])
nums.remove(nums[i])
return sum13(nums)
except:
return sum(nums)
return sum(nums)
return sum(nums)
答案 4 :(得分:0)
当您的代码遇到以“ 13”结尾的数组时,它将尝试将“ count”减少13,然后再减少数字“ 13”之后的数字,并且该数字不存在。这就是为什么它会破裂。
您可以通过将范围“ for i in range()”减小1来解决此问题(对于range in len(len(nums)-1)),并分别处理最后的13情况
此外,先加数字然后再减13会造成双扣13或末尾加13的问题。我认为,与其将所有数字相加然后减去13,还不如将13及其后的数字替换为零,并在最后进行加法,这是一个更好的策略。
这是更正的代码。
def sum13(nums):
if nums[-1] == 13:
nums[-1] = 0
for i in range(len(nums)-1):
if nums[i] == 13:
nums[i] = 0
nums[i+1] = 0
return sum(nums)
答案 5 :(得分:0)
这是递归解决方案
def sum13(nums, i=0):
#exit condition
if(len(nums) == i):
return 0
if nums[i] == 13:
l = len(nums) - 1
return sum13(nums, i + (1 if i == l else 2))
return nums[i] + sum13(nums, i + 1)
答案 6 :(得分:0)
def sum13(nums):
if not nums:
return 0
if 13 not in nums:
return sum(nums)
else:
i = 0
sum_ = 0
while i < len(nums):
v = nums[i]
if v != 13:
sum_ += v
i += 1
else:
i += 2
return sum_