chacoderのブログ

競技プログラミングそのほか

Pythonはじめました(2)

FOR 文

PythonのFOR文はリストの要素に対し繰り返し処理を行うのでC++のFOR文とはだいぶ雰囲気が違います。
C++のFOR文のような処理をする場合,組み込み関数のrange()を使う方法があります。

for i in range(5)
    print(i)

出力

0
1
2
3
4

コード例 ABC127B - Algae

B - Algae

r,D,X2000 = map(int,input().split())
for i in range(10):
  X2000=r*X2000-D
  print(X2000)

While 文

インデントを使った記述に気を付ければC++と同じように使えます。

ABC156B
NがK進数で何ケタになるかもとめなさい

B - Digits

N,K=map(int,input().split())
ans=0
while N>0:
  N//=K
  ans+=1
print(ans)

文字列操作 - 文字列中の文字の変換

文字列は内容を変更できないimmutableな型だといわれます。

文字列中の1文字を変更したい場合、変更したい箇所よりも前+変更した箇所+変更したい箇所よりも後を新しく組み立てて記述します。

文字列SのN文字目より前はS[:N-1]、N文字目はS[N]、N文字目より後はS[N:]で記述できます。

コード例 ABC126A - Changing a Character

A - Changing a Character

n文字の英大文字からなる文字列sのk文字目を小文字に変換した文字列を出力します。

n,k = map(int,input().split())
s = input()
print(s[:k-1]+s[k-1].lower()+s[k:])
print('\n')

リスト

リストにはいろいろなメソッドがあるようですが、まずはデータ入力からです。

スペース区切りのデータを入力します。

コード例

ABC132B - Ordinary Number

B - Ordinary Number

n=int(input())
p=list(map(int,input().split()))
cnt=0
for i in range(n-2):
  if p[i]<p[i+1]<p[i+2] or p[i]>p[i+1]>p[i+2]:
    cnt+=1
print(cnt)

The Zen of Python

import thisを実行すると The Zen of Pythonが表示されます。

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!