python - 寻找更优雅的解决方案

标签 python

<分区>

Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 7 (every 6 will be followed by at least one 7). Return 0 for no numbers.

sum67([1, 2, 2]) ? 5
sum67([1, 2, 2, 6, 99, 99, 7]) ? 5
sum67([1, 1, 6, 7, 2]) ? 4
def sum67(nums):
    dontadd = 0
    sum = 0
    for i in range(0, len(nums)):
        if dontadd == 0:
            if nums[i] == 6:
                dontadd = 1
            else:
                sum += nums[i]
        else:
            if nums[i] == 7:
                dontadd = 0
            else:
                pass# nothing happens. It is useful as a placeholder when a statement is required syntactically
    return sum

从codingbat中寻找更优雅的解决方案来解决这个问题。这个答案似乎并不像它应该的那样直观

最佳答案

如果我们可以只删除不需要的元素,那么我们可以使用简单的求和。这是一个例子:

def sum67(nums):
    nums=nums[:]
    while 6 in nums:
        i=nums.index(6)
        j=nums.index(7,i)
        del nums[i:j+1]
    return sum(nums)

首先,我们使用nums=nums[:] 进行复制。调用者可能不希望 nums 发生变化。

nums.index(6) 找到第一个值为 6 的元素的索引。nums.index(7,i) 找到第一个元素的索引索引 i 之后值为 7 的第一个元素。 del nums[i:j+1] 然后删除ij范围内的元素,包括j处的元素

关于python - 寻找更优雅的解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10184714/

相关文章:

python - 如何在 python 中嗅探 HTTP 数据包?

python - 试图将多边形数据分成 x 和 y 坐标,但得到错误 "' MultiPolygon' 对象没有属性 'exterior'”

python - ReportLab 表格布局

python - 根据不同 DataFrame 中的条件从 DataFrame 中消除行

python - 通过 SleekXMPP 发送 facebook 消息

python - Theano 损失函数中的对数行列式

python - 修补 Python 模拟中函数调用中的一处出现

python - 如何在Python中调用程序的 'catch' stdin、stdout、stderr?

python - gunicorn 和/或 celery : What is the way get the best out of both?

Python:生成一个包含 5 列的多值真值表,其中每列可以取一组特定的值