【问题标题】:Codility error: Invalid result type, Integer expected, NilClass foundCodility 错误:无效的结果类型,需要整数,找到 NilClass
【发布时间】:2021-09-13 00:07:09
【问题描述】:

编辑:由斯蒂芬解决 但是:现在,剩下的唯一问题是:为什么较短的解决方案性能如此差(结果:100%,性能:32%,结果:66%),而较长的版本性能更好但似乎产生更差的结果(60%、50%、55%)?

原始问题的开始: 我目前正在尝试 Codility 演示测试,要解决的问题是找到不包含在给定数组中的 0 以上的最小整数。 这是我在两个不同版本中的代码,结果相同。输出是正确的,但编译器抛出上述错误,导致测试失败。当在 SO 上查找此错误时,这似乎是 Codility 上的常见错误。

# you can write to stdout for debugging purposes, e.g.
# puts "this is a debug message"

def solution(a)
  # write your code in Ruby 2.2
  num = 1
  a=a.sort
  a.uniq!
  a.each do |x|
    if x == num then
      num += 1
      next
    else
      break
    end
  end
  puts num
end

def solution(a)
  # write your code in Ruby 2.2
  num = 1
  while a.include?(num) do
    num += 1
  end
  puts num
end

结果:

Compilation successful.

Example test:   [1, 3, 6, 4, 1, 2]
Output (stderr):
Invalid result type, Integer expected, NilClass found
Output:
5
RUNTIME ERROR (tested program terminated with exit code 1)

Example test:   [1, 2, 3]
Output (stderr):
Invalid result type, Integer expected, NilClass found
Output:
4
RUNTIME ERROR (tested program terminated with exit code 1)

Example test:   [-1, -3]
Output (stderr):
Invalid result type, Integer expected, NilClass found
Output:
1
RUNTIME ERROR (tested program terminated with exit code 1)

Producing output might cause your solution to fail performance tests.
You should remove code that produces output before you submit your solution.

Detected some errors.

我真的不明白出了什么问题。数组只包含整数,num 是整数,一切都是整数,但编译器说它是 NIL。我能做什么?

编辑:相同的代码在 SoloLearn 应用程序和我的本地机器上运行没有错误。

【问题讨论】:

  • puts 的返回值为 nil。您的方法可能应该返回结果而不是打印它。
  • 是的,这就是解决方案。谢谢!

标签: ruby null integer runtime-error


【解决方案1】:

输出正确但编译器抛出上述错误,导致测试失败

虽然puts 生成输出,但它的返回值nil

puts 123
# 123      # <- output
#=> nil    # <- return value

我假设您的方法应该返回该值,而不是将其打印到标准输出。

您可以通过删除方法最后一行中的 puts 来解决此问题:

def solution(a)
  num = 1
  while a.include?(num)
    num += 1
  end
  num # <- without "puts"
end

要生成调试输出,您可以在返回值之前的单独行中添加puts num,例如:

def solution(a)
  # ...

  puts num  # <- prints num
  num       # <- returns num
end

或者您可以使用p 输出对象的inspect 值并返回对象:

def solution(a)
  # ...

  p num  # <- prints num.inspect and returns num
end

关于性能:尝试了解代码必须做什么才能获得结果。 “短”解决方案增加 num 并检查它是否包含在数组中。但是包含检查必须遍历数组(至少直到匹配元素)。因此,对于num 的每一个增量,您都是从头开始遍历数组。

您可以通过使用Set 进行查找来显着加快这一速度:

require 'set'

def solution(a)
  set = Set.new(a)
  num = 1
  num += 1 while set.include?(num)
  num
end

【讨论】:

  • 谢谢,这个分数是 100%。我必须阅读有关设置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-21
  • 1970-01-01
  • 2021-11-16
  • 2019-02-21
相关资源
最近更新 更多