【问题标题】:Why this code is not working for specific type of data?为什么此代码不适用于特定类型的数据?
【发布时间】:2020-11-07 17:26:29
【问题描述】:
def find_even_index(arr):
    for a in arr:
        b = arr.index(a)
        if sum(arr[b+1:]) == sum(arr[:b]):
            return b
    return -1

find_even_index([20,10,30,10,10,15,35])
>>> -1

我的代码适用于所有类型的数据,除非它在数字之前或之后遇到相同的数字。其他 10 的索引没有变化。为什么?

【问题讨论】:

  • arr.index(a) 返回匹配a 的第一个索引。如果有重复,它不会做你期望的。
  • 你为什么要遍历元素?只需遍历索引:for b in range(len(arr)):
  • 谢谢@Barmar,你是最棒的:)

标签: python python-3.x for-loop if-statement sum


【解决方案1】:

只需写出@Barmar 在他的 cmets (+1) 中建议的解决方案:

def find_even_index(array):
    for index in range(len(array)):
        if sum(array[:index]) == sum(array[index + 1:]):
            return index

    return -1

print(find_even_index([20, 10, 30, 10, 10, 15, 35]))

或者,如果我们想避免大量调用sum(),并充分利用enumerate(),我们可以尝试:

def find_even_index(array):
    total = sum(array)

    partial_sum = 0

    for index, number in enumerate(array):
        if total - partial_sum == number:
            return index

        partial_sum += number * 2

    return -1

【讨论】:

    【解决方案2】:

    list.index() 函数只会返回最靠近列表开头的指定对象的索引。您可以改为使用 enumerate 遍历每个对象索引旁边的列表:

    def find_even_index(arr):
        for i, a in enumerate(arr): # For index, number in arr
            b = i
            if sum(arr[b+1:]) == sum(arr[:b]):
                return b
        return -1
    
    print(find_even_index([20,10,30,10,10,15,35]))
    

    输出:

    3
    

    【讨论】:

    • 如果不使用a,为什么还要使用enumerate()
    • @Barmar 好吧,我经常看到这种情况发生。
    猜你喜欢
    • 1970-01-01
    • 2020-11-09
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    • 1970-01-01
    • 2019-08-28
    相关资源
    最近更新 更多