【问题标题】:What is wrong with this cumulative sum function, and is there a better way to write the function?这个累积和函数有什么问题,有没有更好的方法来编写函数?
【发布时间】:2022-01-27 02:57:31
【问题描述】:

功能:

def comulative_sum(arr):
    arr1 = []
    for number in range(1, len(arr)):
        sum1 = 0
        for number1 in range(0, arr[number]):
            sum1 += number1
        arr1.append(sum1)
    return arr1
arr = [1, 2, 3, 4]
print(comulative_sum(arr))

输出:

[3, 6, 10]

预期输出:

[1, 3, 6, 10]

我尝试过切片 ([1:], [0:number) 而不是 range 函数。还是没有结果。

【问题讨论】:

  • 预期输出对于累积和是否正确?不应该是 1 4 10 20 还是我误解了它
  • 嗯,是的,但我不小心将输出复制到输入和输出中。我的错。
  • 如果您不告诉 IDE 打印结果,它会打印结果吗?你试过print(comulative_sum(arr)).
  • 好的,谢谢。

标签: python arrays python-3.x list arraylist


【解决方案1】:

编写此函数的更好方法是简单地使用itertools.accumulate(),它就是这样做的:

>>> import itertools
>>> print(list(itertools.accumulate([1,2,3,4]))
[1, 3, 6, 10]

【讨论】:

  • 这确实是非学术环境中的正确答案+1
【解决方案2】:

你不需要循环两次

def cum_sum(x):
    result = []
    current_sum = 0
    for value in x:
        current_sum += value
        result.append(current_sum)
    return result

【讨论】:

    【解决方案3】:

    多个问题:

    • 在第一个循环中,您需要将范围直到 len() + 1,因为最后一个数字是 len(),然后第二个循环中的最后一个数字是 len() - 1,这也是索引。
    • 在第二个循环中,不是一直到 number,而是一直到数组中的原始数字。

    固定代码:

    def comulative_sum(arr):
        arr1 = []
        for number in range(1, len(arr)+1):
            sum1 = 0
            for number1 in range(0, number):
                sum1 += arr[number1]
            arr1.append(sum1)
        return arr1
    arr = [1, 2, 3, 4]
    print(comulative_sum(arr))
    

    如果您希望改进此代码而不使用内置累积,您可以这样做:

    def comulative_sum(input_list):
        output = []
        sum_ = 0  # The underscore is to avoid renaming the built-in sum()
        for i in input_list:
            sum_ += i
            output.append(sum_)
        return output
    
    input_list = [1, 2, 3, 4]
    print(comulative_sum(input_list))
    

    优点:

    1. 更好的变量命名。
    2. 代码嵌套更少。
    3. 更易于整体代码可读性。
    4. 更快的代码(无需在每次迭代中重新计算所有内容)

    【讨论】:

      【解决方案4】:

      我内置了您的解决方案。此版本依赖于 Python 的索引循环,并且还解决了可能的数字“0”。

      def cumulative_sum(arr):
          arr1 = []
          # Python does the hard work for you, it loops through each value on the list
          for value in arr:
              sum1 = 0
              # Range is going to have a list as follows [0, ... , value-1]
              for number1 in range(0, value):
                  sum1 += number1
              # Adding 'value' to sum1 because the loop did not add the last value
              arr1.append(sum1+value)
          return arr1
      
      arr = [1, 3, 6, 10]
      # Calling the function with 'print' to make sure the results are displayed
      print(cumulative_sum(arr))
      

      【讨论】:

        【解决方案5】:

        for 循环只会处理从索引 1 到数组末尾的数字。因此索引 0 将被忽略。

        工作功能:

        def comulative_sum(arr):
        arr1 = []
        for number in arr[:len(arr)]:
            sum1 = 0
            for number1 in arr[0:number]:
                sum1 += number1
            arr1.append(sum1)
        return arr1
        arr = [1, 2, 3, 4]
        print(comulative_sum(arr))
        

        所有改变的只是第一个和第二个 for 循环中的索引。

        【讨论】:

          猜你喜欢
          • 2021-09-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-03-16
          • 2020-04-05
          • 2013-08-18
          相关资源
          最近更新 更多