第一回 オフラインリアルタイムどう書くの参考問題の解答をPythonで書いてみた


import re
import itertools

SPEC = {
  "suit": ["S","H","D","C"],
  "rank": ["2","3","4","5","6","7","8","9","10","J","Q","K","A"],
  "hand": (
    ("4K", lambda x: max(snds(uniq_cnt(snds(x)))) == 4),
    ("FH", lambda x: sorted(snds(uniq_cnt(snds(x)))) == sorted((2,3))),
    ("3K", lambda x: max(snds(uniq_cnt(snds(x)))) == 3),
    ("2P", lambda x: sorted(snds(uniq_cnt(snds(x)))) == sorted((2,2,1))),
    ("1P", lambda x: sorted(snds(uniq_cnt(snds(x)))) == sorted((2,1,1,1))),
    ("--", lambda x: True),
  )
}

def snds(l):
    return [v for (k,v) in l]

def uniq_cnt(l):
    return [(x[0],len(list(x[1]))) for x in itertools.groupby(sorted(l))]

def parser(suit,rank,**kwargs):
    return re.compile("([{suits}]+)([{ranks}]+)".format(suits=''.join(suit),ranks=''.join(rank)))

def main(arg):
    ls = parser(**arg['spec']).findall(arg['input'])
    print list( (k for (k,f) in arg['spec']['hand'] if f(ls)) )[0]

if __name__ == "__main__":
    import sys
    arg={
      "spec": SPEC,
      "input": sys.argv[1],
    }
    main(arg)