基本的にC++で書いていますが、ABC169のような問題が来たときにpythonが使えたら楽だなと思ったので、ABCのC問題埋めしながら、2問ぐらいpythonで実装してました。知らないことばかりなのでメモしていきます。
目次
1.ABC073C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import Counter | |
def main(): | |
n = int(input()) | |
a = [] | |
for i in range(n): | |
a.append(int(input())) | |
counter = Counter(a) | |
ans = 0 | |
for key, value in counter.items(): | |
if value % 2 == 1: | |
ans += 1 | |
print(ans) | |
main() |
連続する要素をカウントするのに、groupbyがあります。また、要素の出現回数をまとめてカウントするものにcollections.Counterがあります。
C++で書くとちょっとめんどくさい出現回数のカウントが一発です。楽ちん。
2.ABC159D
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
n = int(input()) | |
a = list(map(int, input().split())) | |
x = [0] * max(a) | |
for i in a: | |
x[i - 1] += 1 | |
all = 0 | |
def nc2(n): | |
return int(n * (n - 1) / 2) | |
for j in x: | |
if j >= 2: | |
all += nc2(j) | |
for i in range(n): | |
if x[a[i]-1] >= 2: | |
print(all-x[a[i]-1]+1) | |
else: | |
print(all) |
pythonの自作関数は使う前ならどこでもいいっぽい。
あと、pythonは++や–が使えないので、+=1や-=1で書く必要があるようです。
3.ARC086D
pythonでどうやって実装するんだろうと思って提出を見ていたら、pythonらしく書いている提出があって、すげーってなりました。
from collections import Counter N, K = map(int,input().split()) C = Counter(list(map(int,input().split()))) print(sum(sorted(list(C.values()), reverse=True)[K:]))
まず1で書いたcollections.Counterで整数の要素をリストに入れます。
そして、6行目がすごくpythonっぽいです。
print()
これは標準出力になります。
print(sum())
これで総和を出力できます。
print(sum(sorted()))
リストをソートしたものの総和を出力します。
print(sum(sorted(list(C.values()), reverse=True)))
リストCに格納されているvalueを降順にソートし、その総和を出力できます。
print(sum(sorted(list(C.values()), reverse=True)[K:]))
最後に[K:]が付いています。これはスライス操作です。今回、リストのK-1番目~リストの最後までの総和を求める必要があります。そのため、こういうことをしているようです。
スライス操作は
sequence[start:stop]
と書くので、今回は降順にソートしたリストをK-1番目から最後までスライスするという意味になります。
こういうのを息をするように書けるようになりたいものです。
4.参考文献
Pythonでリストをソートするsortとsortedの違い
pythonではインクリメント・デクリメントに++や–は使えない