Python 2.7、412文字
import re,collections as C
r,C=re.findall,C.Counter
def g(m,h,c,v):
try:return t(m,h,c+int(v))
except:
if m[v]:return t(m-C({v:1}),h,c)
def t(m,h,c):return any(g(m,h[1:],c,v)for v in h[0].split('/'))if h else sum(m.values())>=c
def f(m,c):m=C(r(r'\w',m));c=[filter(None, x)for x in zip(*r(r'(\w+/\w+)|(\d+)|(\w)',c))];m.subtract(C(c[2]));print all(x>=0 for x in m.values())*t(m,c[0],sum(int(x)for x in c[1]))
関数f
はチェックを行うものです。マナプールとコストを文字列引数として受け取り、マナ1
がコストを満たした場合などに出力し0
ます。たとえば、f('{R},{R},{G},{B},{R}', '{4},{R}')
prints 1
です。
Ungolfed、それは基本的にこのように見えます
import re
from collections import Counter
def helper(mana, hybrids, colorless, option):
try:
option = int(option) # See if option is an integer
# For colorless hybrid, just add the value to the colorless amount
# to check at the end.
return check_hybrids(mana, hybrids, colorless + option)
except ValueError: # Option is a mana letter
# For colored hybrid costs, check if any of that color is
# available, then try to pay the rest of the cost with 1 less
# of that color.
if mana[option] >= 0:
return check_hybrids(mana - Counter({option: 1}), hybrids, colorless)
else:
return False
def check_hybrids(mana, hybrids, colorless):
'''Check whether the given mana pool can pay the given hybrid costs and colorless costs'''
if hybrids:
# For each option in the first hybrid cost, check whether the
# rest of the cost can be paid after paying that cost
return any(helper(mana, hybrids[1:], colorless, option) for option in hybrids[0].split('/'))
else:
# When there are no remaining hybrid costs, if there is enough
# remaining mana to pay the colorless costs, we have success
return sum(m.values()) > colorless
def can_cast(mana_str, cost_str):
mana = Counter(re.findall(r'\w', mana_str))
# transpose to get separate lists of hybrid, colorless, and colored symbols
cost = zip(*re.findall(r'(\w+/\w+)|(\d+)|(\w)',cost_str))
cost = [filter(None, sublist) for sublist in cost] # Remove unfound symbols
mana.subtract(Counter(cost[2]))
# After subtracting the single-colored cost from the mana pool, if
# anything in the mana pool is negative, we didn't have enough to
# pay for that color.
if any(x <=0 for x in mana.values()):
return False
return check_hybrids(mana, cost[0], sum(int(x)for x in cost[1]))