From 95c7f84ddf4d20a05350924f5dd3ad4fb7c430f2 Mon Sep 17 00:00:00 2001
From: Guillaume Saupin <guillaume.saupin@cea.fr>
Date: Wed, 29 Feb 2012 17:09:34 +0100
Subject: [PATCH] Try to fix issue.

---
 sympy/core/mul.py |   10 ++++++----
 1 files changed, 6 insertions(+), 4 deletions(-)

diff --git a/sympy/core/mul.py b/sympy/core/mul.py
index 3bcca7e..a169994 100644
--- a/sympy/core/mul.py
+++ b/sympy/core/mul.py
@@ -264,12 +264,13 @@ def flatten(cls, seq):
                     o1 = nc_part.pop()
                     b1,e1 = o1.as_base_exp()
                     b2,e2 = o.as_base_exp()
-                    new_exp = e1 + e2
                     # Only allow powers to combine if the new exponent is
                     # not an Add. This allow things like a**2*b**3 == a**5
                     # if a.is_commutative == False, but prohibits
                     # a**x*a**y and x**a*x**b from combining (x,y commute).
-                    if b1==b2 and (not new_exp.is_Add):
+                    if b1==b2 :
+                      new_exp = e1 + e2
+                      if not new_exp.is_Add:
                         o12 = b1 ** new_exp
 
                         # now o12 could be a commutative object
@@ -278,7 +279,9 @@ def flatten(cls, seq):
                             continue
                         else:
                             nc_seq.insert(0, o12)
-
+                      else:
+                        nc_part.append(o1)
+                        nc_part.append(o)
                     else:
                         nc_part.append(o1)
                         nc_part.append(o)
@@ -492,7 +495,6 @@ def _handle_for_oo(c_part, coeff_sign):
 
 
     def _eval_power(b, e):
-
         # don't break up NC terms: (A*B)**3 != A**3*B**3, it is A*B*A*B*A*B
         coeff, b = b.as_coeff_Mul()
         bc, bnc = b.args_cnc()
-- 
1.7.9

