我在Ruby中进行编程练习以确定字符串是否是回文结构。以下是我提出的建议:
dat %>%
count(year, col2 = complete.cases(column2)) %>%
ungroup() %>%
mutate(col2 = factor(col2, labels = c('unknown','known')))
返回以下内容:
# Write a method that takes a string and returns true if it is a
# palindrome. A palindrome is a string that is the same whether written
# backward or forward. Assume that there are no spaces; only lowercase
# letters will be given.
#
# Difficulty: easy.
def palindrome?(string)
iterations=string.length/2
is_palindrome=true
i=0
while i<iterations
if string[i] != string[string.length-i-1]
puts("string is not a palindrome")
is_palindrome=false
end
i+=1
end
return is_palindrome
end
# These are tests to check that your code is working. After writing
# your solution, they should all print true.
puts("\nTests for #palindrome?")
puts("===============================================")
puts('palindrome?("abc") == false: ' + (palindrome?('abc') == false).to_s)
puts('palindrome?("abcba") == true: ' + (palindrome?('abcba') == true).to_s)
puts('palindrome?("z") == true: ' + (palindrome?('z') == true).to_s)
puts("===============================================")
第一个输出应该是&#34; false&#34;,我无法弄清楚为什么它没有返回。它打印&#34;字符串不是回文&#34;,所以我希望它也设置&#34; is_palindrome&#34;变量为&#34; false&#34;并返回。
答案 0 :(得分:3)
就您的解决方案而言,我认为您错误地认为您的代码按预期工作。当然false == false
是真的,所以palindrome?("abc') == false is true
。
虽然与您的解决方案没有直接关系,但如何使用内置的reverse
ruby功能
def palindrome?(string):
string == string.reverse
end
答案 1 :(得分:0)
免责声明:此答案无法解答您的问题,other answer更快。
如果你想测试你的代码,你也应该使用单元测试。
一个例子:
# Write a method that takes a string and returns true if it is a
# palindrome. A palindrome is a string that is the same whether written
# backward or forward. Assume that there are no spaces; only lowercase
# letters will be given.
#
# Difficulty: easy.
def palindrome?(string)
iterations=string.length/2
is_palindrome=true
i=0
while i<iterations
if string[i] != string[string.length-i-1]
#~ puts("string is not a palindrome")
is_palindrome=false
end
i+=1
end
return is_palindrome
end
# These are tests to check that your code is working. After writing
# your solution, they should all print true.
require 'minitest/autorun'
class FirstLetterTest < Minitest::Test
def test_abc
refute(palindrome?('abc'), "'abc' is detected as a palindrome, but it isn't")
end
def test_abcba
assert(palindrome?('abcba'), "'abcba' is not detected as a palindrome")
end
def test_z
assert(palindrome?('z'), "'z' is detected as a palindrome, but it isn't")
end
end
我删除了您的puts("string is not a palindrome")
- 它会混淆输出。