我正在用Ruby进行编程练习,以确定字符串是否是回文。以下是我想出的:
# 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("===============================================")这将返回以下内容:
Tests for #palindrome?
===============================================
string is not a palindrome
palindrome?("abc") == false: true
palindrome?("abcba") == true: true
palindrome?("z") == true: true
===============================================第一个输出应该是"false",我不知道为什么它不返回那个输出。它会打印"string不是回文“,所以我希望它也会将"is_palindrome”变量设置为"false“并返回它。
发布于 2016-04-09 12:00:42
就您的解决方案而言,我认为您错误地理解了代码的工作方式。当然,false == false是真的,所以palindrome?("abc') == false is true。
虽然与您的解决方案没有直接关系,但是使用ruby的内置reverse功能如何?
def palindrome?(string):
string == string.reverse
end发布于 2016-04-09 18:14:42
免责声明:这个答案没有回答你的问题,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") --它混淆了输出。
https://stackoverflow.com/questions/36516433
复制相似问题