0
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.

超初心者が書く! Project Euler を Python で解いてみた! Problem4

Posted at

Problem4

使われている関数の説明がメインです。

問題文

左右どちらから読んでも同じ値になる数を回文数という. 2桁の数の積で表される回文数のうち, 最大のものは 9009 = 91 × 99 である.
では, 3桁の数の積で表される回文数の最大値を求めよ.

方針

100×100 ~ 999×999 を全て計算し、n = reverse:n となった n をlistに突っ込む。
                ↓
max関数で最大のものを引っ張ってくる。

解答&解説

Palindrome.py
def Palindrome_Count (start, stop):
    list = []
    for a in range (start, stop):
        for b in range (start, stop):
            if str (a * b) == str (a * b) [::-1] :
                list.append (a * b)
    return max (list)

print (Palindrome_Count(100, 1000))

for文を2つ使って3桁の数をつくっている。
5行目で回文になっているかを判定させている。[::-1]はスライス関数というものである。(後述)
あとは、回文になっているのをlistに突っ込んで、最大の回文を出力している。

スライス関数

スライス関数を使うとリストや文字列から一部分を選択して値を取得することが可能!
例えば、

test.py
list = [0,1,2,3,4,5,6,7,8,9]
print(list[1:7])
print(list[5:9])
str = "0123456789"
print(str[1:7])
print(str[5:9])
[1, 2, 3, 4, 5, 6]
[5, 6, 7, 8]
234567
6789

のように [ start : stop ] で記述される。(range関数のやつと同じ)
listでも文字列でも考え方は同じである。
また、同じということは [ start : stop : step ] とも書くことができる。

test2.py
list = [0,1,2,3,4,5,6,7,8,9]
print(list[2:10:2])
print(list[10:5:-1])
str = "0123456789"
print(str[2:10:2])
print(str[10:5:-1])
[2, 4, 6, 8]
[9, 8, 7, 6]
2468
9876

そして、次のように値を省略することも可能である。

test3.py
list = [0,1,2,3,4,5,6,7,8,9]
print(list[4::1])
print(list[:8:2])
print(list[::3])
print(list[5::-1])
print(list[::-1])
str = "0123456789"
print(str[4::1])
print(str[:8:2])
print(str[::3])
print(str[5::-1])
print(str[::-1])
[4, 5, 6, 7, 8, 9]
[0, 2, 4, 6]
[0, 3, 6, 9]
[5, 4, 3, 2, 1, 0]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
456789
0246
0369
543210
9876543210

ちなみに、範囲外の値をスライス関数に入力してもErrorにはならない。
空の値が返ってくるだけだ。

test4.py
list = [0,1,2,3,4,5,6,7,8,9]
print(list[6:16])
print(list[16:20])
str = "0123456789"
print(str[6:16])
print(str[16:20])
[6, 7, 8, 9]
[]
6789

最後に

投稿期間は空くものだと思います。(必死の言い訳)

0
0
0

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
0
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?