LoginSignup
1
0

More than 5 years have passed since last update.

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

Posted at

プログラマ脳を鍛える

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 で記述が長くなるときに改行で"\"を使うことを知った。

1
0
5

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