fork download
  1. def p(s):
  2. r=[]
  3. while s and(S:=s[0])!=')':
  4. if S.isalpha():r+=S,
  5. if'('==S:r+=(K:=p(s[1:]))[0],;s=K[1]
  6. s=s[1:]
  7. return r,s
  8. F=lambda x:(O:=ord(str(x)[0]))<92and(64<O<91or all(F(i)for i in x[-2:]))
  9. R=lambda x:[i for i in x if i]
  10. def f(s,l=0,r=0):
  11. if F(s):
  12. J=[]
  13. while s:S=s.pop(0);J+=[[S,s.pop(0)]if~-len(s)>0==F(s[0])else S]
  14. c=[f([*J[0]])]if(t:=F(J[0])==0)else[];s=J[t:];c+=[f(R([l,s[0],r]))]if(S:=sum(map(F,s))%2)else[];s=s[S:]
  15. while s:
  16. if F(s[0]):a,b=s[:2];c+=a,f(R([l,b,r]))if F(b)else f(b),;s=s[2:]
  17. else:c+=s[0],;s=s[1:]
  18. return f(c)
  19. c=[]
  20. while s:c+=[f(j,c and 0==F(c[-1])and c.pop(),r=f(s))]if F(j:=s.pop(0))and list==type(j)else[j]
  21. return c
  22. P=lambda e,l=0:e if str==type(e)else'('*(Y:=l>=1<len(e))+''.join(P(i,l+1)for i in e)+')'*Y
  23. M=lambda s:P(f(p(s)[0]))
  24.  
  25. print(M('x F G y'))
  26. print(M('F x G y'))
  27. print(M('x F y G z'))
  28. print(M('(F x) G H y'))
  29. print(M('(F G H) x'))
  30. print(M('(u G H) x'))
  31. print(M('(G H) x'))
  32. print(M('x (F G H) y'))
  33. print(M('x (u G H) y'))
  34. print(M('x (G H) y'))
  35. print(M('x ((D a) F G (u H J) K) y'))
  36. print(M('x(XY)y'))
  37. print(M('uKKKv'))
  38. print(M('U(xVW)yZa'))
  39. print(M('MnP(QRsTU)VWx'))
  40. print(M('x(XXxYYYdDD)y'))
  41. print(M('a((DEF)GHJ)Kb'))
  42. print(M('c((k(PQRSTU)m)(VW)(XY)(ZA)BCD)n'))
  43.  
Success #stdin #stdout 0.09s 14028KB
stdin
Standard input is empty
stdout
xFGy
FxGy
xFyGz
(Fx)GHy
((Fx)G(Hx))
(uG(Hx))
(G(Hx))
((xFy)G(xHy))
(uG(xHy))
(G(xHy))
((Da)F(uH((xGy)J(xKy))))
(X(xYy))
uKKKv
U(xV(W(yZa)))
MnP((Q(VWx))(Rs)T(U(VWx)))
((xXy)(Xx)Y(xYy)(Yd)D(xDy))
((D((aG(Kb))H(aJ(Kb))))E(F((aG(Kb))H(aJ(Kb)))))
(V((P(kQm)R(kSm)T(kUm))W(Z((X(cYn))A((cBn)C(cDn))))))