简体   繁体   English

如何使用列表切片来完成此操作?

[英]How can I accomplish this using list slicing?

SUMMER OF '69: Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least one 9). SUMMER OF '69:返回数组中数字的总和,除了忽略以 6 开头并延伸到下一个 9 的数字部分(每个 6 后面至少有一个 9)。 Return 0 for no numbers.如果没有数字,则返回 0。

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

This is the problem.这就是问题。 I have been trying to solve this using list slicing but have been unable to.我一直在尝试使用列表切片来解决这个问题,但一直无法解决。 Note: 9 can only be trailing 6, not before 6.注意:9 只能在 6 之后,不能在 6 之前。

Here's what my logic is- I found out the index of 6 and assigned it to a variable and I found the variable of 9 and assigned a variable to it too.这就是我的逻辑 - 我找到了 6 的索引并将其分配给一个变量,我找到了 9 的变量并为其分配了一个变量。 The other two conditions are satisfied but the condition with 9 doesn't get satisfied no matter what I try.其他两个条件都满足了,但是无论我尝试什么,都不能满足 9 的条件。

Here is some code from my side.这是我这边的一些代码。 Please excuse my bad programming skills.请原谅我糟糕的编程技巧。

def summer_69(arr):
    if 6 not in arr:
        return sum(arr)
    elif 6 and 9 in arr:
        i = arr.index(6)
        y = arr.index(9)
        sxy = sum(arr[i:y])
        return sum(arr) - sxy
    else:
        i = arr.index(6)
        return sum(arr[:i])

For an array [4, 5, 6, 7, 8, 9] I am getting the output 18.对于数组 [4, 5, 6, 7, 8, 9],我得到的是 output 18。

Done without slicing.无需切片即可完成。

def summer_69(l):
    sign, count = False, 0
    for num in l:
        if num == 6:
            sign = True
        if not sign:
            count += num
        if num == 9:
            sign = False
    return count

my solution is:我的解决方案是:

def sum67(nums):
    add = True
    sum1 =0
    for i in range(len(nums)):
        if add:
            if nums[i] == 6:
                add = False
            else:
                sum1 += nums[i]
        else:
            if nums[i] == 7:
                add= True
    return sum1
  
  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM