Repository: sympy/sympy

Issue:
factor_list() error Python3
```
Following function call generate an error in Python3 but work well in Python2.

>>> factor_list(x*(x+y))

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/thilinarmtb/GSoC/sympy/sympy/polys/polytools.py", line 5675, in factor_list
    return _generic_factor_list(f, gens, args, method='factor')
  File "/home/thilinarmtb/GSoC/sympy/sympy/polys/polytools.py", line 5423, in _generic_factor_list
    fp = _sorted_factors(fp, method)
  File "/home/thilinarmtb/GSoC/sympy/sympy/polys/polytools.py", line 5322, in _sorted_factors
    return sorted(factors, key=key)
TypeError: unorderable types: list() < int()


Similarly following calls generate the same error:
[1] factor_list(y*(x+y)),  factor_list(x*y + y**2)
[2] factor_list(x*(x+y+z)), factor_list(x**2+x*y+x*z)
[3] factor_list((x + 1)*(x + y))

But the following don't:
[4] factor_list(x*(x**2 + y**2)), factor_list(x**3 + x*y**2) 
[5] factor_list(x**3 - x),  factor_list(x*(x**2 - 1))
[6] factor_list(x**2 + x*y + x + y)
[7] factor_list((x + z)*(x + y)), factor_list(x**2 + x*z + y*x + y*z)

Here [6] is mathematically same as [3]. But only [3] gives the error.
```
Original issue for #7067: http://code.google.com/p/sympy/issues/detail?id=3968
Original author: https://code.google.com/u/115610317529675726783/
Original owner: https://code.google.com/u/101069955704897915480/


Discussion:
smichr: @jksuom @asmeurer , I think I got the problem fixed. I'm still a bilt puzzled by what I was seeing since that was an old change that I don't think is represented anywhere in the current PR. Perhaps the force update and online editing of this PR caused a glitch.
smichr: @jksuom , you were right. The behavior you were seeing was consistent with the behavior in master but was wrong. While f(x) and f(-x) will cover the same integers, f(x) and -f(x) will not. I now only make two simplifications (which are also a bit more robust). 

Patch:
diff --git a/sympy/core/operations.py b/sympy/core/operations.py
index a0869f8459..85037bbef7 100644
--- a/sympy/core/operations.py
+++ b/sympy/core/operations.py
@@ -367,7 +367,7 @@ def make_args(cls, expr):
         if isinstance(expr, cls):
             return expr.args
         else:
-            return (expr,)
+            return (sympify(expr),)
 
 
 class ShortCircuit(Exception):
@@ -443,23 +443,12 @@ def _new_args_filter(cls, arg_sequence, call_cls=None):
     @classmethod
     def make_args(cls, expr):
         """
-        Return a sequence of elements `args` such that cls(*args) == expr
-
-        >>> from sympy import Symbol, Mul, Add
-        >>> x, y = map(Symbol, 'xy')
-
-        >>> Mul.make_args(x*y)
-        (x, y)
-        >>> Add.make_args(x*y)
-        (x*y,)
-        >>> set(Add.make_args(x*y + y)) == set([y, x*y])
-        True
-
+        Return a set of args such that cls(*arg_set) == expr.
         """
         if isinstance(expr, cls):
             return expr._argset
         else:
-            return frozenset([expr])
+            return frozenset([sympify(expr)])
 
     @property
     @cacheit
diff --git a/sympy/polys/polytools.py b/sympy/polys/polytools.py
index b15983594c..e05c0f90e9 100644
--- a/sympy/polys/polytools.py
+++ b/sympy/polys/polytools.py
@@ -5622,12 +5622,12 @@ def _sorted_factors(factors, method):
         def key(obj):
             poly, exp = obj
             rep = poly.rep.rep
-            return (exp, len(rep), rep)
+            return (exp, len(rep), len(poly.gens), rep)
     else:
         def key(obj):
             poly, exp = obj
             rep = poly.rep.rep
-            return (len(rep), exp, rep)
+            return (len(rep), len(poly.gens), exp, rep)
 
     return sorted(factors, key=key)
 
diff --git a/sympy/sets/fancysets.py b/sympy/sets/fancysets.py
index 7e1d2bb970..d819ea4f59 100644
--- a/sympy/sets/fancysets.py
+++ b/sympy/sets/fancysets.py
@@ -1,14 +1,16 @@
 from __future__ import print_function, division
 
 from sympy.logic.boolalg import And
+from sympy.core.add import Add
 from sympy.core.basic import Basic
 from sympy.core.compatibility import as_int, with_metaclass, range, PY3
-from sympy.sets.sets import (Set, Interval, Intersection, EmptySet, Union,
-                             FiniteSet, imageset)
-from sympy.core.sympify import _sympify, sympify, converter
+from sympy.core.expr import Expr
+from sympy.core.function import Lambda, _coeff_isneg
 from sympy.core.singleton import Singleton, S
 from sympy.core.symbol import Dummy, symbols, Wild
-from sympy.core.function import Lambda
+from sympy.core.sympify import _sympify, sympify, converter
+from sympy.sets.sets import (Set, Interval, Intersection, EmptySet, Union,
+                             FiniteSet, imageset)
 from sympy.utilities.misc import filldedent, func_name
 
 
@@ -154,22 +156,32 @@ def _boundary(self):
 
     def _eval_imageset(self, f):
         expr = f.expr
-        if len(f.variables) > 1:
+        if not isinstance(expr, Expr):
             return
-        n = f.variables[0]
 
-        a = Wild('a')
-        b = Wild('b')
+        if len(f.variables) > 1:
+            return
 
-        match = expr.match(a*n + b)
-        if match[a].is_negative:
-            expr = -expr
+        n = f.variables[0]
 
+        # f(x) + c and f(-x) + c cover the same integers
+        # so choose the form that has the fewest negatives
+        c = f(0)
+        fx = f(n) - c
+        f_x = f(-n) - c
+        neg_count = lambda e: sum(_coeff_isneg(_) for _ in Add.make_args(e))
+        if neg_count(f_x) < neg_count(fx):
+            expr = f_x + c
+
+        a = Wild('a', exclude=[n])
+        b = Wild('b', exclude=[n])
         match = expr.match(a*n + b)
-        if match[a] is S.One and match[b].is_integer:
-            expr = expr - match[b]
+        if match and match[a]:
+            # canonical shift
+            expr = match[a]*n + match[b] % match[a]
 
-        return ImageSet(Lambda(n, expr), S.Integers)
+        if expr != f.expr:
+            return ImageSet(Lambda(n, expr), S.Integers)
 
 
 class Reals(with_metaclass(Singleton, Interval)):
@@ -253,17 +265,26 @@ def _is_multivariate(self):
     def _contains(self, other):
         from sympy.matrices import Matrix
         from sympy.solvers.solveset import solveset, linsolve
-        from sympy.utilities.iterables import iterable, cartes
+        from sympy.utilities.iterables import is_sequence, iterable, cartes
         L = self.lamda
+        if is_sequence(other):
+            if not is_sequence(L.expr):
+                return S.false
+            if len(L.expr) != len(other):
+                raise ValueError(filldedent('''
+    Dimensions of other and output of Lambda are different.'''))
+        elif iterable(other):
+                raise ValueError(filldedent('''
+    `other` should be an ordered object like a Tuple.'''))
+
+        solns = None
         if self._is_multivariate():
-            if not iterable(L.expr):
-                if iterable(other):
-                    return S.false
+            if not is_sequence(L.expr):
+                # exprs -> (numer, denom) and check again
+                # XXX this is a bad idea -- make the user
+                # remap self to desired form
                 return other.as_numer_denom() in self.func(
                     Lambda(L.variables, L.expr.as_numer_denom()), self.base_set)
-            if len(L.expr) != len(self.lamda.variables):
-                raise NotImplementedError(filldedent('''
-    Dimensions of input and output of Lambda are different.'''))
             eqs = [expr - val for val, expr in zip(other, L.expr)]
             variables = L.variables
             free = set(variables)
@@ -292,14 +313,35 @@ def _contains(self, other):
                         raise NotImplementedError
                 solns = cartes(*[solns[s] for s in variables])
         else:
-            # assume scalar -> scalar mapping
-            solnsSet = solveset(L.expr - other, L.variables[0])
-            if solnsSet.is_FiniteSet:
-                solns = list(solnsSet)
+            x = L.variables[0]
+            if isinstance(L.expr, Expr):
+                # scalar -> scalar mapping
+                solnsSet = solveset(L.expr - other, x)
+                if solnsSet.is_FiniteSet:
+                    solns = list(solnsSet)
+                else:
+                    msgset = solnsSet
             else:
-                raise NotImplementedError(filldedent('''
-                Determining whether an ImageSet contains %s has not
-                been implemented.''' % func_name(other)))
+                # scalar -> vector
+                for e, o in zip(L.expr, other):
+                    solns = solveset(e - o, x)
+                    if solns is S.EmptySet:
+                        return S.false
+                    for soln in solns:
+                        try:
+                            if soln in self.base_set:
+                                break  # check next pair
+                        except TypeError:
+                            if self.base_set.contains(soln.evalf()):
+                                break
+                    else:
+                        return S.false  # never broke so there was no True
+                return S.true
+
+        if solns is None:
+            raise NotImplementedError(filldedent('''
+            Determining whether %s contains %s has not
+            been implemented.''' % (msgset, other)))
         for soln in solns:
             try:
                 if soln in self.base_set:
@@ -315,10 +357,15 @@ def is_iterable(self):
     def _intersect(self, other):
         from sympy.solvers.diophantine import diophantine
         if self.base_set is S.Integers:
+            g = None
             if isinstance(other, ImageSet) and other.base_set is S.Integers:
-                f, g = self.lamda.expr, other.lamda.expr
-                n, m = self.lamda.variables[0], other.lamda.variables[0]
-
+                g = other.lamda.expr
+                m = other.lamda.variables[0]
+            elif other is S.Integers:
+                m = g = Dummy('x')
+            if g is not None:
+                f = self.lamda.expr
+                n = self.lamda.variables[0]
                 # Diophantine sorts the solutions according to the alphabetic
                 # order of the variable names, since the result should not depend
                 # on the variable name, they are replaced by the dummy variables
@@ -329,13 +376,14 @@ def _intersect(self, other):
                 if solns_set == set():
                     return EmptySet()
                 solns = list(diophantine(f - g))
-                if len(solns) == 1:
-                    t = list(solns[0][0].free_symbols)[0]
-                else:
-                    return None
 
-                # since 'a' < 'b'
-                return imageset(Lambda(t, f.subs(a, solns[0][0])), S.Integers)
+                if len(solns) != 1:
+                    return
+
+                # since 'a' < 'b', select soln for n
+                nsol = solns[0][0]
+                t = nsol.free_symbols.pop()
+                return imageset(Lambda(n, f.subs(a, nsol.subs(t, n))), S.Integers)
 
         if other == S.Reals:
             from sympy.solvers.solveset import solveset_real
@@ -504,39 +552,17 @@ def _intersect(self, other):
             if not all(i.is_number for i in other.args[:2]):
                 return
 
-            o = other.intersect(Interval(self.inf, self.sup))
-            if o is S.EmptySet:
-                return o
-
-            # get inf/sup and handle below
-            if isinstance(o, FiniteSet):
-                assert len(o) == 1
-                inf = sup = list(o)[0]
-            else:
-                assert isinstance(o, Interval)
-                sup = o.sup
-                inf = o.inf
-
-            # get onto sequence
-            step = abs(self.step)
-            ref = self.start if self.start.is_finite else self.stop
-            a = ref + ceiling((inf - ref)/step)*step
-            if a not in other:
-                a += step
-            b = ref + floor((sup - ref)/step)*step
-            if b not in other:
-                b -= step
-            if self.step < 0:
-                a, b = b, a
-            # make sure to include end point
-            b += self.step
-
-            rv = Range(a, b, self.step)
-            if not rv:
-                return S.EmptySet
-            return rv
-
-        elif isinstance(other, Range):
+            # trim down to self's size, and represent
+            # as a Range with step 1
+            start = ceiling(max(other.inf, self.inf))
+            if start not in other:
+                start += 1
+            end = floor(min(other.sup, self.sup))
+            if end not in other:
+                end -= 1
+            return self.intersect(Range(start, end + 1))
+
+        if isinstance(other, Range):
             from sympy.solvers.diophantine import diop_linear
             from sympy.core.numbers import ilcm
 
@@ -641,7 +667,6 @@ def _updated_range(r, first):
         else:
             return
 
-
     def _contains(self, other):
         if not self:
             return S.false
@@ -807,6 +832,30 @@ def __getitem__(self, i):
                 raise IndexError("Range index out of range")
             return rv
 
+    def _eval_imageset(self, f):
+        from sympy.core.function import expand_mul
+        if not self:
+            return S.EmptySet
+        if not isinstance(f.expr, Expr):
+            return
+        if self.size == 1:
+            return FiniteSet(f(self[0]))
+        if f is S.IdentityFunction:
+            return self
+
+        x = f.variables[0]
+        expr = f.expr
+        # handle f that is linear in f's variable
+        if x not in expr.free_symbols or x in expr.diff(x).free_symbols:
+            return
+        if self.start.is_finite:
+            F = f(self.step*x + self.start)  # for i in range(len(self))
+        else:
+            F = f(-self.step*x + self[-1])
+        F = expand_mul(F)
+        if F != expr:
+            return imageset(x, F, Range(self.size))
+
     @property
     def _inf(self):
         if not self:
diff --git a/sympy/sets/sets.py b/sympy/sets/sets.py
index 395138ba32..5d1f3a3cb5 100644
--- a/sympy/sets/sets.py
+++ b/sympy/sets/sets.py
@@ -2033,7 +2033,7 @@ def imageset(*args):
     Examples
     ========
 
-    >>> from sympy import Interval, Symbol, imageset, sin, Lambda
+    >>> from sympy import S, Interval, Symbol, imageset, sin, Lambda
     >>> from sympy.abc import x, y
 
     >>> imageset(x, 2*x, Interval(0, 2))
@@ -2050,6 +2050,14 @@ def imageset(*args):
     >>> imageset(lambda y: x + y, Interval(-2, 1))
     ImageSet(Lambda(_x, _x + x), [-2, 1])
 
+    Expressions applied to the set of Integers are simplified
+    to show as few negatives as possible and linear expressions
+    are converted to a canonical form. If this is not desirable
+    then the unevaluated ImageSet should be used.
+
+    >>> imageset(x, -2*x + 5, S.Integers)
+    ImageSet(Lambda(x, 2*x + 1), Integers())
+
     See Also
     ========
 
diff --git a/sympy/solvers/diophantine.py b/sympy/solvers/diophantine.py
index d293f6b39c..f85bf48485 100644
--- a/sympy/solvers/diophantine.py
+++ b/sympy/solvers/diophantine.py
@@ -86,6 +86,8 @@ def diophantine(eq, param=symbols("t", integer=True)):
         base = term[0]
 
         var_t, jnk, eq_type = classify_diop(base)
+        if not var_t:
+            continue
         solution = diop_solve(base, param)
 
         if eq_type in ["linear", "homogeneous_ternary_quadratic", "general_pythagorean"]:


Test patch:
diff --git a/sympy/core/tests/test_operations.py b/sympy/core/tests/test_operations.py
index 0a2a68b3bb..c34feba3d4 100644
--- a/sympy/core/tests/test_operations.py
+++ b/sympy/core/tests/test_operations.py
@@ -2,6 +2,7 @@
 from sympy.core.operations import LatticeOp
 from sympy.utilities.pytest import raises
 from sympy.core.sympify import SympifyError
+from sympy.core.add import Add
 
 # create the simplest possible Lattice class
 
@@ -34,6 +35,7 @@ def test_lattice_print():
 
 
 def test_lattice_make_args():
-    assert join.make_args(0) == {0}
-    assert join.make_args(1) == {1}
     assert join.make_args(join(2, 3, 4)) == {S(2), S(3), S(4)}
+    assert join.make_args(0) == {0}
+    assert list(join.make_args(0))[0] is S.Zero
+    assert Add.make_args(0)[0] is S.Zero
diff --git a/sympy/polys/tests/test_polytools.py b/sympy/polys/tests/test_polytools.py
index b3f68c68c4..e2c796fd9a 100644
--- a/sympy/polys/tests/test_polytools.py
+++ b/sympy/polys/tests/test_polytools.py
@@ -3157,3 +3157,9 @@ class foo(Expr):
 def test_to_rational_coeffs():
     assert to_rational_coeffs(
         Poly(x**3 + y*x**2 + sqrt(y), x, domain='EX')) == None
+
+
+def test_factor_terms():
+    # issue 7067
+    assert factor_list(x*(x + y)) == (1, [(x, 1), (x + y, 1)])
+    assert sqf_list(x*(x + y)) == (1, [(x, 1), (x + y, 1)])
diff --git a/sympy/sets/tests/test_fancysets.py b/sympy/sets/tests/test_fancysets.py
index 08d1610904..ebee5c5668 100644
--- a/sympy/sets/tests/test_fancysets.py
+++ b/sympy/sets/tests/test_fancysets.py
@@ -112,7 +112,7 @@ def test_halfcircle():
     assert not halfcircle.is_iterable
 
 
-def test_ImageSet_iterator_not_injetive():
+def test_ImageSet_iterator_not_injective():
     L = Lambda(x, x - x % 2)  # produces 0, 2, 2, 4, 4, 6, 6, ...
     evens = ImageSet(L, S.Naturals)
     i = iter(evens)
@@ -303,84 +303,49 @@ def test_range_range_intersection():
 
 
 def test_range_interval_intersection():
-    empty = Range(0)
     p = symbols('p', positive=True)
     assert isinstance(Range(3).intersect(Interval(p, p + 2)), Intersection)
-    assert Range(0, 4, 3).intersect(Interval(1, 2)) is S.EmptySet
-    for line, (r, i) in enumerate([
-        # Intersection with intervals
-        (Range(0, 10, 1), Interval(2, 6)),
-        (Range(0, 2, 1), Interval(2, 6)),
-        (Range(0, 3, 1), Interval(2, 6)),
-        (Range(0, 4, 1), Interval(2, 6)),
-        (Range(0, 7, 1), Interval(2, 6)),
-        (Range(0, 10, 1), Interval(2, 6)),
-        (Range(2, 3, 1), Interval(2, 6)),
-        (Range(2, 4, 1), Interval(2, 6)),
-        (Range(2, 7, 1), Interval(2, 6)),
-        (Range(2, 10, 1), Interval(2, 6)),
-        (Range(3, 4, 1), Interval(2, 6)),
-        (Range(3, 7, 1), Interval(2, 6)),
-        (Range(3, 10, 1), Interval(2, 6)),
-        (Range(6, 7, 1), Interval(2, 6)),
-        (Range(6, 10, 1), Interval(2, 6)),
-        (Range(7, 10, 1), Interval(2, 6)),
-        (Range(0, 10, 2), Interval(3, 5)),
-        (Range(1, 10, 2), Interval(2, 6)),
-        (Range(2, 10, 2), Interval(2, 6)),
-        (Range(3, 10, 2), Interval(2, 6)),
-        (Range(6, 10, 2), Interval(2, 6)),
-        (Range(10), Interval(5.1, 6.9)),
-
-        # Open Intervals are removed
-        (Range(0, 10, 1), Interval(2, 6, True, True)),
-
-        # Try this with large steps
-        (Range(0, 100, 10), Interval(15, 55)),
-
-
-        # Infinite range
-        (Range(0, oo, 2), Interval(-1, 5)),
-        (Range(-oo, 4, 3), Interval(-10, 20)),
-        (Range(-oo, 4, 3), Interval(-10, -5)),
-
-        # Infinite interval
-        (Range(-3, 0, 3), Interval(-oo, 0)),
-        (Range(0, 10, 3), Interval(3, oo)),
-        (Range(0, 10, 3), Interval(-oo, 5)),
-
-        # Infinite interval, infinite range start
-        (Range(-oo, 1, 3), Interval(-oo, 5)),
-        (Range(-oo, 1, 3), Interval(-oo, -3)),
-
-        # Infinite interval, infinite range end
-        (Range(0, oo, 3), Interval(5, oo)),
-        (Range(0, oo, 3), Interval(-5, oo)),
-        (Range(0, oo, 3), Interval(-oo, 5)),
-
-        ]):
-
-        for rev in range(2):
-            if rev:
-                r = r.reversed
-            result = r.intersection(i)
-
-            msg = "line %s: %s.intersect(%s) != %s" % (line, r, i, result)
-            if result is S.EmptySet:
-                assert (
-                    r.sup < i.inf or
-                        r.sup == i.inf and i.left_open) or (
-                    r.inf > i.sup or
-                        r.inf == i.sup and i.right_open), msg
-            else:
-                checks = a, b, c, d = [
-                    result.inf in i or result.inf == i.inf,
-                    result.inf - abs(result.step) not in i or \
-                        result.inf == r.inf,
-                    result.sup in i or result.sup == i.sup,
-                    result.sup + abs(result.step) not in i or \
-                    result.sup == r.sup]
-                assert all(_ for _ in checks), msg
+    assert Range(4).intersect(Interval(0, 3)) == Range(4)
+    assert Range(4).intersect(Interval(-oo, oo)) == Range(4)
+    assert Range(4).intersect(Interval(1, oo)) == Range(1, 4)
+    assert Range(4).intersect(Interval(1.1, oo)) == Range(2, 4)
+    assert Range(4).intersect(Interval(0.1, 3)) == Range(1, 4)
+    assert Range(4).intersect(Interval(0.1, 3.1)) == Range(1, 4)
+    assert Range(4).intersect(Interval.open(0, 3)) == Range(1, 3)
+    assert Range(4).intersect(Interval.open(0.1, 0.5)) is S.EmptySet
+
+
+def test_Integers_eval_imageset():
+    ans = ImageSet(Lambda(x, 2*x + S(3)/7), S.Integers)
+    im = imageset(Lambda(x, -2*x + S(3)/7), S.Integers)
+    assert im == ans
+    im = imageset(Lambda(x, -2*x - S(11)/7), S.Integers)
+    assert im == ans
+    y = Symbol('y')
+    assert imageset(x, 2*x + y, S.Integers) == \
+        imageset(x, 2*x + y % 2, S.Integers)
+
+    _x = symbols('x', negative=True)
+    eq = _x**2 - _x + 1
+    assert imageset(_x, eq, S.Integers).lamda.expr == _x**2 + _x + 1
+    eq = 3*_x - 1
+    assert imageset(_x, eq, S.Integers).lamda.expr == 3*_x + 2
+
+    assert imageset(x, (x, 1/x), S.Integers) == \
+        ImageSet(Lambda(x, (x, 1/x)), S.Integers)
+
+
+def test_Range_eval_imageset():
+    a, b, c = symbols('a b c')
+    assert imageset(x, a*(x + b) + c, Range(3)) == \
+        imageset(x, a*x + a*b + c, Range(3))
+    eq = (x + 1)**2
+    assert imageset(x, eq, Range(3)).lamda.expr == eq
+    eq = a*(x + b) + c
+    r = Range(3, -3, -2)
+    imset = imageset(x, eq, r)
+    assert imset.lamda.expr != eq
+    assert list(imset) == [eq.subs(x, i).expand() for i in list(r)]
 
 
 def test_fun():
@@ -433,26 +398,33 @@ def test_infinitely_indexed_set_1():
     from sympy.abc import n, m, t
     assert imageset(Lambda(n, n), S.Integers) == imageset(Lambda(m, m), S.Integers)
 
-    assert imageset(Lambda(n, 2*n), S.Integers).intersect(imageset(Lambda(m, 2*m + 1), S.Integers)) == \
-            EmptySet()
+    assert imageset(Lambda(n, 2*n), S.Integers).intersect(
+            imageset(Lambda(m, 2*m + 1), S.Integers)) is S.EmptySet
 
-    assert imageset(Lambda(n, 2*n), S.Integers).intersect(imageset(Lambda(n, 2*n + 1), S.Integers)) == \
-            EmptySet()
+    assert imageset(Lambda(n, 2*n), S.Integers).intersect(
+            imageset(Lambda(n, 2*n + 1), S.Integers)) is S.EmptySet
 
-    assert imageset(Lambda(m, 2*m), S.Integers).intersect(imageset(Lambda(n, 3*n), S.Integers)) == \
+    assert imageset(Lambda(m, 2*m), S.Integers).intersect(
+                imageset(Lambda(n, 3*n), S.Integers)) == \
             ImageSet(Lambda(t, 6*t), S.Integers)
 
+    assert imageset(x, x/2 + S(1)/3, S.Integers).intersect(S.Integers) is S.EmptySet
+    assert imageset(x, x/2 + S.Half, S.Integers).intersect(S.Integers) is S.Integers
+
 
 def test_infinitely_indexed_set_2():
-    from sympy import exp
     from sympy.abc import n
     a = Symbol('a', integer=True)
-    assert imageset(Lambda(n, n), S.Integers) == imageset(Lambda(n, n + a), S.Integers)
-    assert imageset(Lambda(n, n), S.Integers) == imageset(Lambda(n, -n + a), S.Integers)
-    assert imageset(Lambda(n, -6*n), S.Integers) == ImageSet(Lambda(n, 6*n), S.Integers)
-    assert imageset(Lambda(n, 2*n + pi), S.Integers) == ImageSet(Lambda(n, 2*n + pi), S.Integers)
-    assert imageset(Lambda(n, pi*n + pi), S.Integers) == ImageSet(Lambda(n, pi*n + pi), S.Integers)
-    assert imageset(Lambda(n, exp(n)), S.Integers) != imageset(Lambda(n, n), S.Integers)
+    assert imageset(Lambda(n, n), S.Integers) == \
+        imageset(Lambda(n, n + a), S.Integers)
+    assert imageset(Lambda(n, n + pi), S.Integers) == \
+        imageset(Lambda(n, n + a + pi), S.Integers)
+    assert imageset(Lambda(n, n), S.Integers) == \
+        imageset(Lambda(n, -n + a), S.Integers)
+    assert imageset(Lambda(n, -6*n), S.Integers) == \
+        ImageSet(Lambda(n, 6*n), S.Integers)
+    assert imageset(Lambda(n, 2*n + pi), S.Integers) == \
+        ImageSet(Lambda(n, 2*n + pi - 2), S.Integers)
 
 
 def test_imageset_intersect_real():
@@ -465,18 +437,15 @@ def test_imageset_intersect_real():
     assert s.intersect(S.Reals) == imageset(Lambda(n, 2*n*pi - pi/4), S.Integers)
 
 
-@XFAIL
-def test_infinitely_indexed_failed_diophantine():
-    from sympy.abc import n, m, t
-    assert imageset(Lambda(m, 2*pi*m), S.Integers).intersect(imageset(Lambda(n, 3*pi*n), S.Integers)) == \
-            ImageSet(Lambda(t, -6*pi*t), S.Integers)
-
-
-@XFAIL
 def test_infinitely_indexed_set_3():
-    from sympy.abc import n
-    assert imageset(Lambda(n, 2*n + 1), S.Integers) == imageset(Lambda(n, 2*n - 1), S.Integers)
-    assert imageset(Lambda(n, 3*n + 2), S.Integers) == imageset(Lambda(n, 3*n - 1), S.Integers)
+    from sympy.abc import n, m, t
+    assert imageset(Lambda(m, 2*pi*m), S.Integers).intersect(
+            imageset(Lambda(n, 3*pi*n), S.Integers)) == \
+        ImageSet(Lambda(t, 6*pi*t), S.Integers)
+    assert imageset(Lambda(n, 2*n + 1), S.Integers) == \
+        imageset(Lambda(n, 2*n - 1), S.Integers)
+    assert imageset(Lambda(n, 3*n + 2), S.Integers) == \
+        imageset(Lambda(n, 3*n - 1), S.Integers)
 
 
 def test_ImageSet_simplification():
@@ -487,6 +456,11 @@ def test_ImageSet_simplification():
             imageset(Lambda(m, sin(tan(m))), S.Integers)
 
 
+def test_ImageSet_contains():
+    from sympy.abc import x
+    assert (2, S.Half) in imageset(x, (x, 1/x), S.Integers)
+
+
 def test_ComplexRegion_contains():
 
     # contains in ComplexRegion
diff --git a/sympy/solvers/tests/test_diophantine.py b/sympy/solvers/tests/test_diophantine.py
index b20b0e25a6..3617763686 100644
--- a/sympy/solvers/tests/test_diophantine.py
+++ b/sympy/solvers/tests/test_diophantine.py
@@ -317,14 +317,11 @@ def test_transformation_to_normal():
 
 
 def test_diop_ternary_quadratic():
-    # Commented out test cases should be uncommented after
-    # the bug with factor_list() gets merged.
-
     assert check_solutions(2*x**2 + z**2 + y**2 - 4*x*y)
     assert check_solutions(x**2 - y**2 - z**2 - x*y - y*z)
     assert check_solutions(3*x**2 - x*y - y*z - x*z)
     assert check_solutions(x**2 - y*z - x*z)
-    #assert check_solutions(5*x**2 - 3*x*y - x*z)
+    assert check_solutions(5*x**2 - 3*x*y - x*z)
     assert check_solutions(4*x**2 - 5*y**2 - x*z)
     assert check_solutions(3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z)
     assert check_solutions(8*x**2 - 12*y*z)
@@ -375,12 +372,9 @@ def test_parametrize_ternary_quadratic():
 
 
 def test_no_square_ternary_quadratic():
-    # Commented out test cases should be uncommented after
-    # the bug with factor_list() gets merged.
-
     assert check_solutions(2*x*y + y*z - 3*x*z)
     assert check_solutions(189*x*y - 345*y*z - 12*x*z)
-    #assert check_solutions(23*x*y + 34*y*z)
+    assert check_solutions(23*x*y + 34*y*z)
     assert check_solutions(x*y + y*z + z*x)
     assert check_solutions(23*x*y + 23*y*z + 23*x*z)
 
@@ -394,24 +388,21 @@ def test_descent():
 
 
 def test_diophantine():
-    # Commented out test cases should be uncommented after
-    # the bug with factor_list() gets merged.
-
     assert check_solutions((x - y)*(y - z)*(z - x))
     assert check_solutions((x - y)*(x**2 + y**2 - z**2))
     assert check_solutions((x - 3*y + 7*z)*(x**2 + y**2 - z**2))
     assert check_solutions((x**2 - 3*y**2 - 1))
-    #assert check_solutions(y**2 + 7*x*y)
-    #assert check_solutions(x**2 - 3*x*y + y**2)
-    #assert check_solutions(z*(x**2 - y**2 - 15))
-    #assert check_solutions(x*(2*y - 2*z + 5))
+    assert check_solutions(y**2 + 7*x*y)
+    assert check_solutions(x**2 - 3*x*y + y**2)
+    assert check_solutions(z*(x**2 - y**2 - 15))
+    assert check_solutions(x*(2*y - 2*z + 5))
     assert check_solutions((x**2 - 3*y**2 - 1)*(x**2 - y**2 - 15))
     assert check_solutions((x**2 - 3*y**2 - 1)*(y - 7*z))
     assert check_solutions((x**2 + y**2 - z**2)*(x - 7*y - 3*z + 4*w))
     # Following test case caused problems in parametric representation
     # But this can be solved by factroing out y.
     # No need to use methods for ternary quadratic equations.
-    #assert check_solutions(y**2 - 7*x*y + 4*y*z)
+    assert check_solutions(y**2 - 7*x*y + 4*y*z)
     assert check_solutions(x**2 - 2*x + 1)
 
 
diff --git a/sympy/solvers/tests/test_solveset.py b/sympy/solvers/tests/test_solveset.py
index 943c783591..00552f09cd 100644
--- a/sympy/solvers/tests/test_solveset.py
+++ b/sympy/solvers/tests/test_solveset.py
@@ -1,5 +1,5 @@
 from sympy import (
-    Abs, Dummy, Eq, Gt, Function,
+    Abs, Dummy, Eq, Gt, Function, Mod,
     LambertW, Piecewise, Poly, Rational, S, Symbol, Matrix,
     asin, acos, acsc, asec, atan, atanh, cos, csc, erf, erfinv, erfc, erfcinv,
     exp, log, pi, sin, sinh, sec, sqrt, symbols,
@@ -105,31 +105,31 @@ def ireal(x, s=S.Reals):
                 imageset(Lambda(n, 2*n*pi - acos(y)), S.Integers)))
 
     assert invert_real(cos(exp(x)), y, x) == \
-        (x, Union(imageset(Lambda(n, log(2*n*pi + acos(y))), S.Integers), \
-                imageset(Lambda(n, log(2*n*pi - acos(y))), S.Integers)))
+        (x, Union(imageset(Lambda(n, log(2*n*pi + Mod(acos(y), 2*pi))), S.Integers), \
+                imageset(Lambda(n, log(2*n*pi + Mod(-acos(y), 2*pi))), S.Integers)))
 
     assert invert_real(sec(x), y, x) == \
         (x, Union(imageset(Lambda(n, 2*n*pi + asec(y)), S.Integers), \
                 imageset(Lambda(n, 2*n*pi - asec(y)), S.Integers)))
 
     assert invert_real(sec(exp(x)), y, x) == \
-        (x, Union(imageset(Lambda(n, log(2*n*pi + asec(y))), S.Integers), \
-                imageset(Lambda(n, log(2*n*pi - asec(y))), S.Integers)))
+        (x, Union(imageset(Lambda(n, log(2*n*pi + Mod(asec(y), 2*pi))), S.Integers), \
+                imageset(Lambda(n, log(2*n*pi + Mod(-asec(y), 2*pi))), S.Integers)))
 
     assert invert_real(tan(x), y, x) == \
-        (x, imageset(Lambda(n, n*pi + atan(y)), S.Integers))
+        (x, imageset(Lambda(n, n*pi + atan(y) % pi), S.Integers))
 
     assert invert_real(tan(exp(x)), y, x) == \
-        (x, imageset(Lambda(n, log(n*pi + atan(y))), S.Integers))
+        (x, imageset(Lambda(n, log(n*pi + atan(y) % pi)), S.Integers))
 
     assert invert_real(cot(x), y, x) == \
-        (x, imageset(Lambda(n, n*pi + acot(y)), S.Integers))
+        (x, imageset(Lambda(n, n*pi + acot(y) % pi), S.Integers))
 
     assert invert_real(cot(exp(x)), y, x) == \
-        (x, imageset(Lambda(n, log(n*pi + acot(y))), S.Integers))
+        (x, imageset(Lambda(n, log(n*pi + acot(y) % pi)), S.Integers))
 
     assert invert_real(tan(tan(x)), y, x) == \
-        (tan(x), imageset(Lambda(n, n*pi + atan(y)), S.Integers))
+        (tan(x), imageset(Lambda(n, n*pi + atan(y) % pi), S.Integers))
 
     x = Symbol('x', positive=True)
     assert invert_real(x**pi, y, x) == (x, FiniteSet(y**(1/pi)))