fork download
  1. import itertools as i
  2. D=dict.fromkeys
  3. I=isinstance
  4. L=len
  5. P=i.product
  6. T=tuple
  7. def w(s,q=[]):
  8. if s:
  9. if q:
  10. if Z:=q[-1][0]:yield from w(s[1:],q[:-1]+[(Z,q[-1][1]+[s[0]])])
  11. yield from w(s[1:],q+[(1>Z,[s[0]])])
  12. else:yield from w(s[1:],q+[(0,[s[0]])]);yield from w(s[1:],q+[(1,[s[0]])])
  13. else:yield T((a,T(set(b)))for a, b in q)
  14. def p(s,l=0):
  15. if L(s)==1:yield T(s);return
  16. n=min(s,key=L)
  17. if m:=[n[x:y+1]for x in range(L(n))for y in range(x,L(n))if all(n[x:y+1]in a for a in s)]:
  18. for q in m:
  19. a,b=[[*filter(None,x)]for x in zip(*[j.split(q,1)for j in s])];x,y=[p(a,1)]if a else[],[p(b,1)]if b else[];yield from P(*(x+[(q,)]+y))
  20. if 1>l:yield(*[(u,)for u in D(a)],q,*[(u,)for u in D(b)])
  21. if 1>l:
  22. for j in w(s):
  23. if~-all(x[0]for x in j):yield from P(*[p(b,1)if a else[b]for a,b in j])
  24. else:s=[x for y in s for x in([[y],y][any(any(j in v for v in s if v!=y)for j in y)])];yield T([(u,)for u in sorted(set(s),key=s.index)])
  25. def e(s):yield from map(''.join,P(*[[k]if I(k,str)else[*e(k),'']for k in s]))
  26. def t(s):
  27. for i in s:
  28. if I(i,str):yield i
  29. elif any(I(j,str)for j in i):yield T(t(i))
  30. else:yield from t(i)
  31. def f(s):s=s.split(', ');return min([((v:=T(t(i))),sum(~-(j in s)for j in e(v)))for i in set(p(s))],key=lambda x:x[1])
  32.  
  33. #main test cases
  34. print(f('their'))
  35. print(f('their, her'))
  36. print(f('her, him'))
  37. print(f('she, he'))
  38. print(f('they, she, he'))
  39. print(f('them, her, him'))
  40. print(f('goca, oc, oca'))
  41. print(f('goca, soca, oc, goce, soce'))
  42. print(f('goca, soca, gsocae, goce, soce'))
  43. print(f('goca, soca, gsxocae, goce, soce, xoce'))
Success #stdin #stdout 0.32s 14124KB
stdin
Standard input is empty
stdout
(('their',), 0)
((('th',), ('h',), 'e', ('ir',), ('r',)), -14)
(('h', ('er',), ('im',)), -2)
((('she',), ('he',)), -2)
(((('t',), ('s',), 'h', ('e', ('y',))), ('he',)), -22)
((('t',), 'h', ('e',), ('m',), ('r',), ('i',)), -30)
((((('g',), 'o'), 'c', ('a',)), ('oca',)), -10)
(((('g',), ('s',), 'o', (('c',), 'a')), ('oc',), (('g',), ('s',), 'o', (('c',), 'e'))), -333)
(((('g',), ('s',), 'o', (('c',), 'a')), ('gsocae',), (('g',), ('s',), 'o', (('c',), 'e'))), -333)
((('goca',), ((('g',), 's', ('x',)), 'o', (('c',), 'a', ('e',))), ('goce',), (('x',), ('s',), 'o', ('c', ('e',)))), -1346)