【问题标题】:Ruby - App Academy Practice Exercise About Condition in While LoopRuby - 关于 While 循环中的条件的应用学院实践练习
【发布时间】:2017-01-17 10:20:41
【问题描述】:

我正在完成App Academy's practice problems 的第一个编码挑战,并且对为#8 附近的 az 提供的解决方案有疑问:

# Write a method that takes a string in and returns true if the letter
# "z" appears within three letters **after** an "a". You may assume
# that the string contains only lowercase letters.
#
# Difficulty: medium.

def nearby_az(string)
  idx1 = 0
  while idx1 < string.length
    if string[idx1] != "a"
      idx1 += 1
      next
    end

    idx2 = idx1 + 1
    while (idx2 < string.length) && (idx2 <= idx1 + 3)
      if string[idx2] == "z"
        return true
      end

      idx2 += 1
    end

    idx1 += 1
  end

  return false
end

# These are tests to check that your code is working. After writing
# your solution, they should all print true.

puts("\nTests for #nearby_az")
puts("===============================================")
    puts('nearby_az("baz") == true: ' + (nearby_az('baz') == true).to_s)
    puts('nearby_az("abz") == true: ' + (nearby_az('abz') == true).to_s)
    puts('nearby_az("abcz") == true: ' + (nearby_az('abcz') == true).to_s)
    puts('nearby_az("a") == false: ' + (nearby_az('a') == false).to_s)
    puts('nearby_az("z") == false: ' + (nearby_az('z') == false).to_s)
    puts('nearby_az("za") == false: ' + (nearby_az('za') == false).to_s)
puts("===============================================")

在第二个while循环中:

 while (idx2 < string.length) && (idx2 <= idx1 + 3)

为什么条件(idx2 &lt; string.length) 是必要的?我在没有它的情况下测试了代码并得到了相同的结果。

感谢您的帮助。

【问题讨论】:

  • 可以说,它是必需的,因为实现不是非常惯用的 Ruby。更惯用的方法可能是基于 string#split

标签: ruby while-loop conditional-statements


【解决方案1】:

为什么需要条件 (idx2 &lt; string.length)?

这不是必要的。当 idx2 超出字符串范围时,它可以防止循环的无意义迭代。

在超出字符串长度的位置寻址字符将返回 nil。 nil 永远不会等于 'z'。所以我们还不如在到达终点时停下来。这就是这里的检查,优化。

在其他情况下,越界访问通常是一种严重的违规行为,并会导致各种问题(通常是崩溃)。所以总是这样做是有意义的。

【讨论】:

    【解决方案2】:

    我知道这并不能回答您的确切问题,并且其他人已经回答了它,但是作为编程的常见情况,有更好的方法。您可以使用正则表达式轻松解决此问题

    def nearby_az(string)
      !(string =~ /a\w{0,3}z/).nil?
    end
    

    正则表达式将匹配模式a,后面有0到3个字符,然后是z。如果不匹配,=~ 操作符会返回nil,所以nil? 方法返回true,意味着字符串附近没有az,所以我们使用! 来反转布尔值,这个方法将返回false

    如果有匹配,=~返回第一个字符的索引,不是nil,所以nil?返回false,我们和之前一样反转它返回true

    只是觉得这可能会有所帮助。

    【讨论】:

      猜你喜欢
      • 2011-02-22
      • 2011-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-03
      • 2016-10-08
      • 1970-01-01
      • 2015-02-27
      相关资源
      最近更新 更多