1
1

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で競プロに挑む日誌 vol.16 ~要素が一種類のリストを作る~

Last updated at Posted at 2018-11-03

現在の目標

  • 2018年内に茶色になる←イマココ
  • ABC の A, B 問題を全部解く
  • 2018年度内に緑色を取得する
  • 水色になったら, APG4b で C++ にも手を出す

今日のおはなし

結論

要素が一種類のリストは, for 文を使うことなくカンタンに作れる.

解いた問題
B-編集

私の解答

my_answer.py
# coding: utf-8
N, Q = map(int, input().split())
an = [0 for _ in range(N)]
#print(an)
 
for _ in range(Q):
    l, r, t = map(int, input().split())
    l -= 1
    r -= 1
    for i in range(r-l+1):
        an[l + i] = t
 
for x in an:
    print(x)

カンタンな方法

list_answer.py
# coding: utf-8
N, Q = map(int, input().split())
an = [0]*N    #<-ココと, 
 
for _ in range(Q):
    l, r, t = map(int, input().split())
    an[l-1:r] = [t]*(r-l+1)    #<- ココ
 
for x in an:
    print(x)

for 文や内包表記使わなくてもカンタンに作れるんですね. 基本は大事です.

参考
http://nekoyukimmm.hatenablog.com/entry/2016/02/26/091217
https://pycarnival.com/one_asterisk/

追記
この方法には, 下記のような罠がありました. 列が全部更新されてしまうようです.

trap.py
a = [[0]*5]*3
print(a)    #-> [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
a[1][1]=1
print(a)    #-> [[0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 1, 0, 0, 0]]

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?