"""Exact ordinary-card rummy partitions for the declared single-deck study model."""
from itertools import combinations
from functools import lru_cache
DECK=[(r,s) for r in range(2,15) for s in range(4)]
def valid_declaration(cards):
 if len(cards)!=13 or len(set(cards))!=13:return False
 groups=[]
 for k in range(3,14):
  for ix in combinations(range(13),k):
   cs=[cards[i] for i in ix];rs=[c[0] for c in cs];ss=[c[1] for c in cs]
   natural_set=k<=4 and len(set(rs))==1 and len(set(ss))==k
   low=sorted(1 if r==14 else r for r in rs);high=sorted(rs)
   run=len(set(ss))==1 and len(set(rs))==k and (high[-1]-high[0]==k-1 or low[-1]-low[0]==k-1)
   if natural_set or run:groups.append((sum(1<<i for i in ix),int(run)))
 byfirst={i:[g for g in groups if g[0]>>i&1] for i in range(13)}
 @lru_cache(None)
 def partition(mask,runs):
  if mask==0:return runs>=2
  bit=(mask&-mask).bit_length()-1
  return any(mask&m==m and partition(mask^m,min(2,runs+r)) for m,r in byfirst[bit])
 return partition((1<<13)-1,0)
def completion_cards(cards,discard):
 fixed=[c for c in cards if c!=discard]
 return [c for c in DECK if c not in cards and valid_declaration(fixed+[c])]
def parse(label):
 suits='♠♥♦♣';r=label[:-1];return ({'J':11,'Q':12,'K':13,'A':14}.get(r,int(r) if r.isdigit() else 0),suits.index(label[-1]))
