LoginSignup
1
2

More than 5 years have passed since last update.

Pythonで競プロに挑む日誌 vol.4 ~and と or~

Last updated at Posted at 2018-09-02

現在の目標

  • 今年の10月内に茶色を取得する ←イマココ
  • 年内に緑色を取得する
  • APG4b で C++ にも手を出す

今日の問題

ABC083B - Some Sums
https://beta.atcoder.jp/contests/abs/tasks/abc083_b

結果

answer1.py
# coding: utf-8
N, A, B = map(int, input().split())

ans = 0
for i in range(1,N+1):
    lis_i = [int(x) for x in list(str(i))]
    val = sum(lis_i)
    if (val >= A) and (val <= B):
        ans += i

print(ans)

# 実行時間:36 ms
# メモリ :2940 KB
# コード長:222 Byte
# 得点  :200/200

すんなり解けたかな, と思います.

内包表記をもっと活用できないかと粘ってみました↓

answer2.py
# coding: utf-8
N, A, B = map(int, input().split())

ans = [i
       for i in range(1,N+1)
       if (sum([int(j) for j in list(str(i))])) >= A and (sum([int(j) for j in list(str(i))])) <= B]

print(sum(ans))

# 実行時間:49 ms
# メモリ :3404 KB
# コード長:215 Byte
# 得点  :200/200

うーん, 粘った割には美しくないですね. あと、実行速度も遅かった.


疑問
answer2 を考える途中で, "&" と "and" の使い分けがよくわからなくなりました.

and_&.py
# and だと正解となる
if (sum([int(j) for j in list(str(i))])) >= A and (sum([int(j) for j in list(str(i))])) <= B]

# & だと不正解
if (sum([int(j) for j in list(str(i))])) >= A & (sum([int(j) for j in list(str(i))])) <= B]

調べてみると, 違いは下記にあるようです.

  • and : bool 演算
  • & : bit 演算

if 文の条件式判定には bool 値が使われるので, and や or を使うのが正しそうだと理解しました. & は 2 進数同士の演算に使うものなんですね.

ただ, answer1 の if 文判定は and でも & でも通ったんですよ... うーむ, よくわからん.

いやぁ, 先は長そうですな. 慌てず焦らず, 楽しみながら続けていこうと思います.

明日やること

ABC088B - Card Game for Two を解く.

1
2
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
2