1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby と Python で解く AtCoder ABC168 A case式

1
Last updated at Posted at 2020-05-17

はじめに

AtCoder Problems の Recommendation を利用して、過去の問題を解いています。
AtCoder さん、AtCoder Problems さん、ありがとうございます。

今回のお題

AtCoder Beginner Contest A - ∴ (Therefore)
Difficulty: 2

今回のテーマ、case式

Ruby

本戦では、if式で解いていますが、editorial

余談ですが,Ruby では case 文がこれにあたり,もっと高機能です.

と書かれていますので、caseで書いてみたいと思います。これまでにcaseを書いたことはないです
まずは、if

ruby.rb
n = gets.to_i
n %= 10
if n == 3
  puts "bon"
elsif n == 0 || n == 1 || n == 6 || n == 8
  puts "pon"
else
  puts "hon"
end
last.rb
n %= 10

10で割った余りで1の位を取得していますが、gets.chompとして文字列としn[-1]とすることもできます。

case.rb
n = gets.chomp
case n[-1]
when "3" then
  puts "bon"
when "0", "1", "6", "8" then
  puts "pon"
else
  puts "hon"
end

editorial の解説にある 高機能 とは,を用いて複数条件を指定することができるという意味です。

Python

python.py
n = int(input()) % 10
if n == 3:
    print("bon")
elif n in {0, 1, 6, 8}:
    print("pon")
else:
    print("hon")

pythonはcaseが無いようなので、似た感じにしてみました。
python のinは SQL のinに似ていますね。

まとめ

  • ABC 168 A を解いた
  • Ruby に詳しくなった
  • Python に詳しくなった

参照したサイト
Python に switch や case 文がないのはなぜですか?
pythonにswitchはないけれど

1
0
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?