1
3

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.

プログラマ脳を鍛える数学パズルをひたすらPythonで:Q3「カードを裏返せ」

Last updated at Posted at 2017-10-29

Q3:カードを裏返せ#

全問Pythonで解いてみようと思ってますのでどうぞよろしくお願いします。

※Q2はあまり面白くないのと学んだこともそんなにないので飛ばします。

問題#

1~100までの番号が書かれた100枚のカードが順番に並べられています。
最初、すべてのカードは裏返しの状態で置かれています。
ある人が2番のカードから、1つおきにカードを裏返していきます。
すると、2, 4, 6, … , 100番のカードが表を向いています。
次に、別の人が、3番のカードから2つおきにカードを裏返していきます。
(裏向きのカードは表を向き、表向いているカードは裏返しされます。)
また、別の人が、4番のカードから3つおきに、カードを裏返してきます。
このようにn番目のカードからn-1つおきにカードを裏返す操作を、
どのカードの向きも変わらなくなるまで続けたとします。
裏向きになっているカードの番号をすべて求めてください。

Code#

まずはrubyでの模範回答

N = 100
cards = Array.new(N, false)

(2..N).each{|i|
    j = i - 1
    while (j < cards.size) do
        cards[j] = !cards[j]
        j += i
    end
}

N.times{|i|
    puts i + 1 if !cards[i]
}

Pythonで書くなら...

N = [True]*100
for i in range(1, 101):
    j = i - 1
    while j < 100:
        N[j] = not N[j]
        j += i

print([k + 1 for k in range(100) if N[k] == False])
# 1, 4, 9, 16, 25, 36, 49, 64, 81, 100

まぁそこまで長くなく無難なCodeになったのではないでしょうか??

今回の学習ポイント#

rubyでの以下のCodeをPythonで書くにはどうしたらいいか。

cards[j] = !cards[j]
puts i + 1 if !cards[i]
N[j] = not N[j]
print([k + 1 for k in range(100) if N[k] == False]) #list内包表記
1
3
4

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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?