見出し画像

paizaの「第1回P共通テスト過去問題 Q2: rot-x」をpythonで解いてみた

import collections

n = int(input())
s = input()
t = input()

l = []
for i in range(n):
    l.append((ord(t[i]) - ord(s[i])) % 26)
c = collections.Counter(l)
x = c.most_common()[0][0]

if len(c) == 1:
    print(f"correct rot-{x}")
elif len(c) == 2 and c.most_common()[1][1] == 1:
    intab = 'abcdefghijklmnopqrstuvwxyz'
    outtab = intab[x:] + intab[:x]
    table = str.maketrans(intab, outtab)
    print(f"fixed {s.translate(table)}")
else:
    print("incorrect")
  • collections.Counter()でCounterオブジェクトを生成。Counterは辞書型dictで、キーは要素、値は出現回数

  • Counterのmost_common()メソッドで、タプル(要素, 出現回数)を出現回数順に並べたリストを取得

  • str.maketrans(intab, outtab)で、文字の置き換え表の作成。intab : 変換前文字列、outtab : 変換後文字列

  • str.tranlate(table)で、複数の文字を一括で変換。文字の入れ替えが可能

(collectionsを使わないコード)

n = int(input())
s = input()
t = input()

d = {}
for i in range(n):
    k = (ord(t[i]) - ord(s[i])) % 26
    d[k] = d.get(k, 0) + 1
l = sorted(d.items(), key = lambda x : x[1], reverse = True)
x = l[0][0]

if len(d) == 1:
    print(f"correct rot-{x}")
elif len(d) == 2 and l[1][1] == 1:
    intab = 'abcdefghijklmnopqrstuvwxyz'
    outtab = intab[x:] + intab[:x]
    table = str.maketrans(intab, outtab)
    print(f"fixed {s.translate(table)}")
else:
    print("incorrect")

この記事が気に入ったらサポートをしてみませんか?