Help us understand the problem. What is going on with this article?

プログラマ脳を鍛える数学パズルをひたすらPythonで:Q1「回文数」

More than 1 year has passed since last update.

プログラマ脳を鍛える

PaizaのスキルチェックにおいてBランクからなかなか抜け出せないので、気分転換も含めプログラマ脳を鍛える数学パズルをPythonで解いていこうと思います。

あと、他言語で書かれているCodeをPythonに変換してみたいという興味もかねて。

問題

問題内容は10進数でも2進数でも8進数でも上から読んでも下から読んでも同じ数字になること。

(例)

  • 10進数:9
  • 2進数:1001
  • 8進数:11

では、9より上の10進数で回文数になる値は何?
というのが問題です。

Code

まずはruby

num = 11
while true
    if num.to_s == num.to_s.reverse &&
        num.to_s(8) == num.to_s(8).reverse &&
        num.to_s(2) == num.to_s(2).reverse
        puts num
        break
    end
    num += 2
end

同じことをPythonで

num = 11

while True:
    if str(num) == str(num)[::-1]\
    and str(format(num, 'b')) == str(format(num, 'b'))[::-1]\
    and str(format(num, 'o')) == str(format(num, 'o'))[::-1]:
        print(num)
        break
    num += 2

もう少し簡単にしてみる

def palindrome(x):
    return str(x) == str(x)[::-1]

n = 11

while True:
    if palindrome(n) and palindrome(format(n, 'b')) and palindrome(format(n, 'o')):
        print(n)
        break
    n += 2

今回の学習ポイント

and とか or で記述が長くなるときに改行で"\"を使うことを知った。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away