将数组中的数字相加,但忽略interval



我是新来的,但我希望我能得到一些帮助。问题是:

SUMMER OF '69:返回数组中所有数字的和,除了忽略以6开头并延伸到下一个9的部分(每个6后面至少有一个9)。如果没有数字则返回0。

summer_69([1,3,5])——>9
summer_69([4,5,6,7,8,9])——>9
summer_69([2,1,6,9,11])——>14

我在论坛上看到一个答案,看起来很简单:

def summer_69(arr):
if 6 and 9 in arr:
c=sum(arr[arr.index(6):arr.index(9)+1)
return sum(arr)-c
else:
return sum(arr)

它工作,但我不明白为什么我必须加1到索引和。有人能给我解释一下吗?

清晰和实际工作实现:

def summer_69(arr):
result = 0
omit = False
for num in arr:
if omit:
if num == 9:
omit = False
elif num == 6:
omit = True
else:
result += num
return result

如果要使用片,请确保为索引搜索提供适当的起始点:

def summer_69(arr):
if 6 not in arr:
return sum(arr)
i6 = arr.index(6)
i9 = arr.index(9, i6)  # the first 9 after the first 6 
return sum(arr[:i6]) + summer_69(arr[i9+1:])

这里,递归将处理后面的部分。

数组切片在这里有更详细的解释,并在您的用例中定义为开始-结束切片的subarray = array[start:end],它指定:

注意:结果包括开始索引,但不包括结束索引。

summer_69函数必须返回数组中不在6到9之间的数的和(包括6和9本身))。若设start为6的索引,end为9索引,则9的索引将排除这不是我们想要做的。

要包含它,我们必须添加+1来选择9后面的元素。

你的代码不工作-if 6 and 9 in arr总是为真-你的else部分永远不会执行-所以即使它产生一些有效的结果,你的代码是无效的,包含错误。

列表试试你的代码
  • 几个6和9
  • 6 - 9前的9对

你的代码不工作:

def summer_69(arr):
if 6 and 9 in arr:
c = sum(arr[arr.index(6):arr.index(9)+1])
return sum(arr) - c
else:                              # never going to happen
return sum(arr)                # never going to happen
assert summer_69([9, 5, 6, 7, 8, 9]) == 9

输出:

assert summer_69([9, 5, 6, 7, 8, 9]) == 9
AssertionError

而且它也不是很有效-因为你迭代数组两次,而你可以一次解决它。


与schwobaseggl的溶液相似但不同:

def summer_69(arr):
s = 0                           # total sum
between_6_and_9 = False         # are we between 6 and 9?
for n in arr:                   # walk over all nums
if n == 6:                  # now we are at/after 6
between_6_and_9 = True
elif between_6_and_9 and n == 9:       # now we are after 9
between_6_and_9 = False
elif between_6_and_9:       # currently ignoring numbers
pass
else:
s += n                  # add it
return s
assert summer_69([1, 3, 5]) == 9
assert summer_69([4, 5, 6, 7, 8, 9]) == 9
assert summer_69([2, 1, 6, 9, 11]) == 14

=比;无异常==所有断言通过。

(我知道我不是在回答这个问题,但无法抗拒)一个接受6到9个块以外的所有内容的过滤器怎么样?

def filter_69(l):
acc = True
for x in l:
if x in [6, 9]:
acc = x == 9
elif acc:
yield x

用法:

sum(filter_69([2, 1, 6, 9, 11]))
14

下标第二部分的+1是为了包含和中的9。

你找到的解决方案不会工作,有几个原因:

  1. 逻辑:表达式6 and 9 in arr没有适当地表达条件(尽管如果列表中有9,它将为True,并且即使错误也会工作)
  2. 语法:下标或arr[…]中缺少右括号
  3. 完整性:解决方案只占一条6 - 9和将会失败如果有多个这样的对列表中的

这是一个更基本的方法,你应该能够

def summer_69(arr):
result = 0                 # resulting sum
addIt  = 1                 # current state of inclusion
for n in arr:              # go through values of the list
if n == 6: addIt = 0   # stop adding on a 6
result += n * addIt    # add values (if adding)
if n == 9: addIt = 1   # resume adding after a 9
return result              # return the filtered sum

最新更新