【问题标题】:Whenever I try run code it says runtime error.How can I fix it.(Hackerrank)每当我尝试运行代码时,它都会显示运行时错误。我该如何修复它。(Hackerrank)
【发布时间】:2020-05-03 16:18:23
【问题描述】:

我是新来这里和 Hackerrank。我正在尝试解决简单的数组求和问题:

Given an array of integers, find the sum of its elements.

For example, if the array , , so return .

Function Description

Complete the simpleArraySum function in the editor below. It must return the sum of the array elements as an integer.

simpleArraySum has the following parameter(s):

ar: an array of integers
Input Format

The first line contains an integer, , denoting the size of the array.
The second line contains  space-separated integers representing the array's elements.

Constraints


Output Format

Print the sum of the array's elements as a single integer.

我正在尝试找到解决方案,但到目前为止我找不到解决方案。它适用于 jupyter notebook。它说:

Traceback (most recent call last):
  File "Solution.py", line 34, in <module>
    result = simpleArraySum(ar)
  File "Solution.py", line 13, in simpleArraySum
    amount=int(input())
EOFError: EOF when reading a line

在输出按钮上显示“标准输出无响应”。这是我的代码:

def simpleArraySum(ar):
    #
    # Write your code here.
    #
    amount=int(input())

    nums=list(map(int,input().split()))

    sums=0

    for i in nums:

        sums+=i

    print(sums)

【问题讨论】:

    标签: python runtime stdout eoferror


    【解决方案1】:

    你可以这样做;

    def sum_array(arr):
        total = 0
        for i in arr:
            total += i
        return total
    

    您的代码存在一些问题。

    • 您希望将数组传递给函数,但还希望用户输入值。
    • 您将输入转换为整数,但之后拆分输入。

    请注意,有很多方法可以在不编写您自己的自定义函数的情况下解决此问题。

    【讨论】:

      【解决方案2】:

      这应该可以正常工作。只需复制此代码并粘贴即可:

      def simpleArraySum(ar):
          #
          # Write your code here.
          #
          sums=0
          for i in nums:
              sums+=i
          return sums
      
      amount = int(input())
      nums = list(map(int,input().split()))
      print(simpleArraySum(nums))
      

      我什么都没做,只是在函数外读取输入。

      【讨论】:

        【解决方案3】:

        这应该适合你:

        amount=int(input())
        nums=list(map(int,input().split()))
        sums=0
        for i in nums:
            sums+=i
        print(sums)
        

        你只有一个问题:
        1. 你只需要对给定数组的所有元素求和,只需求和,你不需要读取用户的输入。这就是我在你的代码,然后在我修改后删除所有内容并编写代码,应该可以工作,一切都会好起来的。

        【讨论】:

          猜你喜欢
          • 2020-10-11
          • 1970-01-01
          • 1970-01-01
          • 2018-12-09
          • 2022-11-07
          • 1970-01-01
          • 1970-01-01
          • 2019-09-23
          • 1970-01-01
          相关资源
          最近更新 更多