2014年1月2日木曜日

Palindrom(回文)

putsとpの違いに騙された。
これだとダメっていわれた。
def is_palindrome(s)
  return s == s.reverse()
end

def run
  if is_palindrome(STDIN.gets.rstrip)
    p "Y"
  else
    p "N"
  end
end

STDIN.gets.to_i.times { run }
pだと"Y"ってかんじでダブルクオテーションがつけられてしまうらしい。どういうことかは知らんけど。
んで、これだといいらしい
def is_palindrome(s)
  return s == s.reverse()
end

def run
  if is_palindrome(STDIN.gets.rstrip)
    puts "Y"
  else
    puts "N"
  end
end

STDIN.gets.to_i.times { run }

とあるぺーじによると、こんな仕組みらしい。こういう意味不明に同じようなやり方が存在するっていうのが、私がRuby大嫌いな理由。pythonみたいにprintだけでコンマの有無で改行の有無が変わる、とかでいいじゃない。
  • p
    引数のオブジェクトを人間に読みやすい形で出力。 文字列はダブル・クォーテーションで囲まれて表示されるので、 末尾にスペースが入っているかどうかも確認できる。 配列やハッシュ(連想配列)もそのままの形で表示する。
  • puts
    引数のオブジェクトの値それぞれに改行をつけて出力。 配列の中身もそれぞれが改行される。 ハッシュ(連想配列)は繋がって表示される。
  • putc
    1文字を出力。引数は1個だけOK。 引数が数字なら、0 〜 255 の範囲の対応する文字を出力 引数が文字列なら、その先頭の1文字を出力。
  • print
    引数を順に出力。 オブジェクト間に改行は自動的には入らないので、必要なら挿入してやる必要がある。
  • printf
    C 言語の printf と同じように、format に従い引数を文字列に変換して出力

A palindrome is a string reads the same from left to right and from right to left. For example: 'abba' is a palindrome, as well as 'aba', but not 'bbaaa.' We want to determine whether strings are palindromes.

The first line of the input will be an integer N (1 <= N <= 10000).

Each of the following N lines represents a single test case, containing a string S (1 <= length of S <= 10000). The string will not contain any spaces or special characters.

*Note* each string will end with '\n' given each line has only one string(test case)
 
For each test case, print 'Y' if S is a palindrome and 'N' if not. No blank line between test cases.

Sample Input/Output
3
aba
bbaa
a
Y
N
Y

0 件のコメント: