1
0

More than 1 year has passed since last update.

【学習記録】 文字列 (paizaランク C 相当)

Posted at

目次

  • 問題文
  • 書いたコード
  • 解答例
  • 学んだこと
  • 振り返り

問題文

詳細はコチラ

問題文の要約

一行目に以降の入力件数を。二行目以降で、スタート時刻と、要する時間のセットを複数行与えられる。

入力例2
2
15:59 0 1
23:20 1 0

出力例2
16:00
00:20

書いたコード

main.py
count = int(input())

def time_change(h, s):
    if s >= 60:
        h += 1
        s -= 60
        if h >= 24:
            h -= 24
    else:
        if h >= 24:
            h -= 24
    if len(str(h)) == 1:
        h = "0" + str(h)
    if len(str(s)) == 1:
        s = "0" + str(s)
    print(str(h) + ":" + str(s))


while count > 0:
    attr = input().split()
    time_change(int(attr[0][:2]) + int(attr[1]) ,int(attr[0][3:])+ int(attr[2]))
    count -= 1

time_changeという関数を作りました。
時間と分数を引数にして、求められている形式で表示する、というものです。

解答例

main.py
N = int(input())

for i in range(N):
    [t, h, m] = input().split() # ['13:00', '1', '30']
    th = int(t[:2]) # 13
    tm = int(t[3:]) # 0
    h = int(h) # 1
    m = int(m) # 30

    ah = th + h
    am = tm + m

    if am >= 60:
        ah += 1
        am -= 60
    if ah >= 24:
        ah -= 24

    ah = str(ah)
    am = str(am)

    if len(ah) == 1:
        ah = "0" + ah
    if len(am) == 1:
        am = "0" + am

    print(ah + ":" + am)

行っていること自体には大きな差はないのですが、可読性に雲泥の差が…。
変数を有効に使って、随時定義していることが一番の違いでしょうか。
私の書いたコードだと何が入っているのか一目で分からない点に大きな問題がありそうです。
if文の乱立もさらに可読性を下げている印象。

学んだこと

  1. 無理せず随時変数を定義すること
  2. ブロックごとに処理をまとめること

一言

動けばいいコードから脱却して、可読性を上げることも意識したいです。
[t, h, m] = input().split()
→この書き方がよく分かっていなかったので次には使えるように復習します。

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