第3回オフラインリアルタイムどう書くの参考問題 pythonで解く


BallCount.py
# -*- coding:utf-8 -*-

# ボールカウントディクショナリの定義と初期化
ball_count_dict = {'o':0, 's':0, 'b':0}

def dict_initialize():
    ball_count_dict['o'] = 0
    ball_count_dict['s'] = 0
    ball_count_dict['b'] = 0

# アウトのカウントアップ
def count_up_o():
    if 2 == ball_count_dict.get('o'):
        ball_count_dict['o'] = 0
        ball_count_dict['s'] = 0
        ball_count_dict['b'] = 0
    elif 2 > ball_count_dict.get('o'):
        ball_count_dict['o'] += 1
        ball_count_dict['s'] = 0
        ball_count_dict['b'] = 0

# ストライクのカウントアップ
def count_up_s(pitch_type):
    if 2 == ball_count_dict['s'] and 's' == pitch_type:
        count_up_o()
    elif 2 > ball_count_dict['s']:
        ball_count_dict['s'] += 1

# ボールのカウントアップ
def count_up_b():
    if 3 > ball_count_dict.get('b'):
        ball_count_dict['b'] += 1
    else:
        ball_count_dict['s'] = 0
        ball_count_dict['b'] = 0

# 実行メソッド
def execute(pitch_types):
    count_list = []
    dict_initialize()
    for pitch_type in pitch_types:

        if 's' == pitch_type:
            count_up_s(pitch_type)

        elif 'f' == pitch_type:
            count_up_s(pitch_type)

        elif 'b' == pitch_type:
            count_up_b()
        elif 'p' == pitch_type:
            count_up_o()
        elif 'h' == pitch_type:
            ball_count_dict['s'] = 0
            ball_count_dict['b'] = 0

        count_list.append(str(ball_count_dict.get('o')) + str(ball_count_dict.get('s')) + str(ball_count_dict.get('b')))

    return count_list

# テスト実行メソッド
def test(pitch_types, exp):
    result = execute(pitch_types)
    if exp == ','.join(result):
        print pitch_types + ' => ' + exp + " : OK"

if __name__ == "__main__":
    test('s' , '010')
    test('sss' , '010,020,100')
    test('bbbb' , '001,002,003,000')
    test('ssbbbb' , '010,020,021,022,023,000')
    test('hsbhfhbh' , '000,010,011,000,010,000,001,000')
    test('psbpfpbp' , '100,110,111,200,210,000,001,100')
    test('ppp' , '100,200,000')
    test('ffffs' , '010,020,020,020,100')
    test('ssspfffs' , '010,020,100,200,210,220,220,000')
    test('bbbsfbppp' , '001,002,003,013,023,000,100,200,000')
    test('sssbbbbsbhsbppp' , '010,020,100,101,102,103,100,110,111,100,110,111,200,000,100')
    test('ssffpffssp' , '010,020,020,020,100,110,120,200,210,000')