def rcollect(expr, *vars):
 if (expr.is_Atom or (not expr.has(*vars))):
  return expr
 else:
  expr = expr.__class__(*[rcollect(arg, *vars) for arg in expr.args])
  if expr.is_Add:
   return collect(expr, vars)
  else:
   return expr

def rcollect ( expr , * vars ) : if ( expr . is_Atom or ( not expr . has ( * vars ) ) ) : return expr else : expr = expr . __class__ ( * [ rcollect ( arg , * vars ) for arg in expr . args ] ) if expr . is_Add : return collect ( expr , vars ) else : return expr
recursively collect sums in an expression .