def test_Dict(): assert str(Dict({1: 1 + x})) == sstr({1: 1 + x}) == "{1: x + 1}" assert str(Dict({ 1: x**2, 2: y * x })) in ("{1: x**2, 2: x*y}", "{2: x*y, 1: x**2}") assert sstr(Dict({1: x**2, 2: y * x})) == "{1: x**2, 2: x*y}"
def test_domains(): X, Y = Die('x', 6), Die('y', 6) x, y = X.symbol, Y.symbol # Domains d = where(X > Y) assert d.condition == (x > y) d = where(And(X > Y, Y > 3)) assert d.as_boolean() == Or(And(Eq(x, 5), Eq(y, 4)), And(Eq(x, 6), Eq(y, 5)), And(Eq(x, 6), Eq(y, 4))) assert len(d.elements) == 3 assert len(pspace(X + Y).domain.elements) == 36 Z = Die('x', 4) raises(ValueError, lambda: P(X > Z)) # Two domains with same internal symbol assert pspace(X + Y).domain.set == FiniteSet(1, 2, 3, 4, 5, 6)**2 assert where(X > 3).set == FiniteSet(4, 5, 6) assert X.pspace.domain.dict == FiniteSet( *[Dict({X.symbol: i}) for i in range(1, 7)]) assert where(X > Y).dict == FiniteSet(*[ Dict({ X.symbol: i, Y.symbol: j }) for i in range(1, 7) for j in range(1, 7) if i > j ])
def test_gcd_terms(): f = 2*(x + 1)*(x + 4)/(5*x**2 + 5) + (2*x + 2)*(x + 5)/(x**2 + 1)/5 + \ (2*x + 2)*(x + 6)/(5*x**2 + 5) assert _gcd_terms(f) == ((Rational(6, 5)) * ((1 + x) / (1 + x**2)), 5 + x, 1) assert _gcd_terms(Add.make_args(f)) == \ ((Rational(6, 5))*((1 + x)/(1 + x**2)), 5 + x, 1) newf = (Rational(6, 5)) * ((1 + x) * (5 + x) / (1 + x**2)) assert gcd_terms(f) == newf args = Add.make_args(f) # non-Basic sequences of terms treated as terms of Add assert gcd_terms(list(args)) == newf assert gcd_terms(tuple(args)) == newf assert gcd_terms(set(args)) == newf # but a Basic sequence is treated as a container assert gcd_terms(Tuple(*args)) != newf assert gcd_terms(Basic(Tuple(S(1), 3*y + 3*x*y), Tuple(S(1), S(3)))) == \ Basic((S(1), 3*y*(x + 1)), (S(1), S(3))) # but we shouldn't change keys of a dictionary or some may be lost assert gcd_terms(Dict((x*(1 + y), S(2)), (x + x*y, y + x*y))) == \ Dict({x*(y + 1): S(2), x + x*y: y*(1 + x)}) assert gcd_terms((2 * x + 2)**3 + (2 * x + 2)**2) == 4 * (x + 1)**2 * (2 * x + 3) assert gcd_terms(0) == 0 assert gcd_terms(1) == 1 assert gcd_terms(x) == x assert gcd_terms(2 + 2 * x) == Mul(2, 1 + x, evaluate=False) arg = x * (2 * x + 4 * y) garg = 2 * x * (x + 2 * y) assert gcd_terms(arg) == garg assert gcd_terms(sin(arg)) == sin(garg) # issue 6139-like alpha, alpha1, alpha2, alpha3 = symbols('alpha:4') a = alpha**2 - alpha * x**2 + alpha + x**3 - x * (alpha + 1) rep = (alpha, (1 + sqrt(5)) / 2 + alpha1 * x + alpha2 * x**2 + alpha3 * x**3) s = (a / (x - alpha)).subs(*rep).series(x, 0, 1) assert simplify(collect(s, x)) == -sqrt(5) / 2 - Rational(3, 2) + O(x) # issue 5917 assert _gcd_terms([S.Zero, S.Zero]) == (0, 0, 1) assert _gcd_terms([2 * x + 4]) == (2, x + 2, 1) eq = x / (x + 1 / x) assert gcd_terms(eq, fraction=False) == eq eq = x / 2 / y + 1 / x / y assert gcd_terms(eq, fraction=True, clear=True) == \ (x**2 + 2)/(2*x*y) assert gcd_terms(eq, fraction=True, clear=False) == \ (x**2/2 + 1)/(x*y) assert gcd_terms(eq, fraction=False, clear=True) == \ (x + 2/x)/(2*y) assert gcd_terms(eq, fraction=False, clear=False) == \ (x/2 + 1/x)/y
def fromdict(cls, name, density): symbol = Symbol(name) domain = SingleFiniteDomain(symbol, frozenset(density.keys())) density = dict((frozenset(((symbol, val), )), prob) for val, prob in density.items()) density = Dict(density) return FinitePSpace.__new__(cls, domain, density)
def __new__(cls, domain, density): density = {sympify(key): sympify(val) for key, val in density.items()} public_density = Dict(density) obj = PSpace.__new__(cls, domain, public_density) obj._density = density return obj
def fromdict(cls, density, symbol=None): symbol = symbol or cls.create_symbol() domain = SingleFiniteDomain(symbol, frozenset(density.keys())) density = dict((frozenset(((symbol, val), )), prob) for val, prob in density.items()) density = Dict(density) return FinitePSpace.__new__(cls, domain, density)
def _density(self): proditer = product( *[iter(space._density.items()) for space in self.spaces]) d = {} for items in proditer: elems, probs = list(zip(*items)) elem = sumsets(elems) prob = Mul(*probs) d[elem] = d.get(elem, S.Zero) + prob return Dict(d)
def __new__(cls, iterable=None, shape=None, **kwargs): shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs) shape = Tuple(*map(_sympify, shape)) cls._check_special_bounds(flat_list, shape) loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else len(flat_list) # Sparse array: if isinstance(flat_list, (dict, Dict)): sparse_array = Dict(flat_list) else: sparse_array = {} for i, el in enumerate(flatten(flat_list)): if el != 0: sparse_array[i] = _sympify(el) sparse_array = Dict(sparse_array) self = Basic.__new__(cls, sparse_array, shape, **kwargs) self._shape = shape self._rank = len(shape) self._loop_size = loop_size self._sparse_array = sparse_array return self
def test_Dict(): x, y, z = symbols('x y z') d = Dict({x: 1, y: 2, z: 3}) assert d[x] == 1 assert d[y] == 2 raises(KeyError, lambda: d[2]) raises(KeyError, lambda: d['2']) assert len(d) == 3 assert set(d.keys()) == {x, y, z} assert set(d.values()) == {S.One, S(2), S(3)} assert d.get(5, 'default') == 'default' assert d.get('5', 'default') == 'default' assert x in d and z in d and 5 not in d and '5' not in d assert d.has(x) and d.has(1) # SymPy Basic .has method # Test input types # input - a Python dict # input - items as args - SymPy style assert (Dict({x: 1, y: 2, z: 3}) == Dict((x, 1), (y, 2), (z, 3))) raises(TypeError, lambda: Dict(((x, 1), (y, 2), (z, 3)))) with raises(NotImplementedError): d[5] = 6 # assert immutability assert set( d.items()) == {Tuple(x, S.One), Tuple(y, S(2)), Tuple(z, S(3))} assert set(d) == {x, y, z} assert str(d) == '{x: 1, y: 2, z: 3}' assert d.__repr__() == '{x: 1, y: 2, z: 3}' # Test creating a Dict from a Dict. d = Dict({x: 1, y: 2, z: 3}) assert d == Dict(d) # Test for supporting defaultdict d = defaultdict(int) assert d[x] == 0 assert d[y] == 0 assert d[z] == 0 assert Dict(d) d = Dict(d) assert len(d) == 3 assert set(d.keys()) == {x, y, z} assert set(d.values()) == {S.Zero, S.Zero, S.Zero}
def test_dict_set(): a, b, c = map(Wild, 'abc') f = 3 * cos(4 * x) r = f.match(a * cos(b * x)) assert r == {a: 3, b: 4} e = a / b * sin(b * x) assert e.subs(r) == r[a] / r[b] * sin(r[b] * x) assert e.subs(r) == 3 * sin(4 * x) / 4 s = set(r.items()) assert e.subs(s) == r[a] / r[b] * sin(r[b] * x) assert e.subs(s) == 3 * sin(4 * x) / 4 assert e.subs(r) == r[a] / r[b] * sin(r[b] * x) assert e.subs(r) == 3 * sin(4 * x) / 4 assert x.subs(Dict((x, 1))) == 1
def __new__(cls, parameters_or_coordsys, definition, limits=None): if isinstance(parameters_or_coordsys, CoordSys3D): parameters = parameters_or_coordsys.base_scalars() elif not (isinstance(parameters_or_coordsys, tuple) or isinstance(parameters_or_coordsys, Tuple)): parameters = (parameters_or_coordsys,) else: parameters = parameters_or_coordsys if not (isinstance(definition, tuple) or isinstance(definition, Tuple)): definition = (definition,) if limits is None: limits = {} for parameter, bounds in limits.items(): if parameter not in parameters: raise ValueError("%s is not listed in parameter tuple" % parameter) if len(bounds) != 2: raise ValueError("Bounds should be in the form (lower_bound, upper_bound)") obj = super().__new__(cls, Tuple(*parameters), Tuple(*definition), Dict(limits)) return obj
def gcd_terms(terms, isprimitive=False, clear=True, fraction=True): """Compute the GCD of ``terms`` and put them together. ``terms`` can be an expression or a non-Basic sequence of expressions which will be handled as though they are terms from a sum. If ``isprimitive`` is True the _gcd_terms will not run the primitive method on the terms. ``clear`` controls the removal of integers from the denominator of an Add expression. When True (default), all numerical denominator will be cleared; when False the denominators will be cleared only if all terms had numerical denominators other than 1. ``fraction``, when True (default), will put the expression over a common denominator. Examples ======== >>> from sympy.core import gcd_terms >>> from sympy.abc import x, y >>> gcd_terms((x + 1)**2*y + (x + 1)*y**2) y*(x + 1)*(x + y + 1) >>> gcd_terms(x/2 + 1) (x + 2)/2 >>> gcd_terms(x/2 + 1, clear=False) x/2 + 1 >>> gcd_terms(x/2 + y/2, clear=False) (x + y)/2 >>> gcd_terms(x/2 + 1/x) (x**2 + 2)/(2*x) >>> gcd_terms(x/2 + 1/x, fraction=False) (x + 2/x)/2 >>> gcd_terms(x/2 + 1/x, fraction=False, clear=False) x/2 + 1/x >>> gcd_terms(x/2/y + 1/x/y) (x**2 + 2)/(2*x*y) >>> gcd_terms(x/2/y + 1/x/y, fraction=False, clear=False) (x + 2/x)/(2*y) See Also ======== factor_terms, sympy.polys.polytools.terms_gcd """ def mask(terms): """replace nc portions of each term with a unique Dummy symbols and return the replacements to restore them""" args = [(a, []) if a.is_commutative else a.args_cnc() for a in terms] reps = [] for i, (c, nc) in enumerate(args): if nc: nc = Mul._from_args(nc) d = Dummy() reps.append((d, nc)) c.append(d) args[i] = Mul._from_args(c) else: args[i] = c return args, dict(reps) isadd = isinstance(terms, Add) addlike = isadd or not isinstance(terms, Basic) and \ is_sequence(terms, include=set) and \ not isinstance(terms, Dict) if addlike: if isadd: # i.e. an Add terms = list(terms.args) else: terms = sympify(terms) terms, reps = mask(terms) cont, numer, denom = _gcd_terms(terms, isprimitive, fraction) numer = numer.xreplace(reps) coeff, factors = cont.as_coeff_Mul() return _keep_coeff(coeff, factors*numer/denom, clear=clear) if not isinstance(terms, Basic): return terms if terms.is_Atom: return terms if terms.is_Mul: c, args = terms.as_coeff_mul() return _keep_coeff(c, Mul(*[gcd_terms(i, isprimitive, clear, fraction) for i in args]), clear=clear) def handle(a): # don't treat internal args like terms of an Add if not isinstance(a, Expr): if isinstance(a, Basic): return a.func(*[handle(i) for i in a.args]) return type(a)([handle(i) for i in a]) return gcd_terms(a, isprimitive, clear, fraction) if isinstance(terms, Dict): return Dict(*[(k, handle(v)) for k, v in terms.args]) return terms.func(*[handle(i) for i in terms.args])
def test_sympy__core__containers__Dict(): from sympy.core.containers import Dict assert _test_args(Dict({x: y, y: z}))
def test_diagram(): A = Object("A") B = Object("B") C = Object("C") f = NamedMorphism(A, B, "f") g = NamedMorphism(B, C, "g") id_A = IdentityMorphism(A) id_B = IdentityMorphism(B) empty = EmptySet # Test the addition of identities. d1 = Diagram([f]) assert d1.objects == FiniteSet(A, B) assert d1.hom(A, B) == (FiniteSet(f), empty) assert d1.hom(A, A) == (FiniteSet(id_A), empty) assert d1.hom(B, B) == (FiniteSet(id_B), empty) assert d1 == Diagram([id_A, f]) assert d1 == Diagram([f, f]) # Test the addition of composites. d2 = Diagram([f, g]) homAC = d2.hom(A, C)[0] assert d2.objects == FiniteSet(A, B, C) assert g * f in d2.premises.keys() assert homAC == FiniteSet(g * f) # Test equality, inequality and hash. d11 = Diagram([f]) assert d1 == d11 assert d1 != d2 assert hash(d1) == hash(d11) d11 = Diagram({f: "unique"}) assert d1 != d11 # Make sure that (re-)adding composites (with new properties) # works as expected. d = Diagram([f, g], {g * f: "unique"}) assert d.conclusions == Dict({g * f: FiniteSet("unique")}) # Check the hom-sets when there are premises and conclusions. assert d.hom(A, C) == (FiniteSet(g * f), FiniteSet(g * f)) d = Diagram([f, g], [g * f]) assert d.hom(A, C) == (FiniteSet(g * f), FiniteSet(g * f)) # Check how the properties of composite morphisms are computed. d = Diagram({f: ["unique", "isomorphism"], g: "unique"}) assert d.premises[g * f] == FiniteSet("unique") # Check that conclusion morphisms with new objects are not allowed. d = Diagram([f], [g]) assert d.conclusions == Dict({}) # Test an empty diagram. d = Diagram() assert d.premises == Dict({}) assert d.conclusions == Dict({}) assert d.objects == empty # Check a SymPy Dict object. d = Diagram(Dict({f: FiniteSet("unique", "isomorphism"), g: "unique"})) assert d.premises[g * f] == FiniteSet("unique") # Check the addition of components of composite morphisms. d = Diagram([g * f]) assert f in d.premises assert g in d.premises # Check subdiagrams. d = Diagram([f, g], {g * f: "unique"}) d1 = Diagram([f]) assert d.is_subdiagram(d1) assert not d1.is_subdiagram(d) d = Diagram([NamedMorphism(B, A, "f'")]) assert not d.is_subdiagram(d1) assert not d1.is_subdiagram(d) d1 = Diagram([f, g], {g * f: ["unique", "something"]}) assert not d.is_subdiagram(d1) assert not d1.is_subdiagram(d) d = Diagram({f: "blooh"}) d1 = Diagram({f: "bleeh"}) assert not d.is_subdiagram(d1) assert not d1.is_subdiagram(d) d = Diagram([f, g], {f: "unique", g * f: "veryunique"}) d1 = d.subdiagram_from_objects(FiniteSet(A, B)) assert d1 == Diagram([f], {f: "unique"}) raises(ValueError, lambda: d.subdiagram_from_objects(FiniteSet(A, Object("D")))) raises(ValueError, lambda: Diagram({IdentityMorphism(A): "unique"}))
def __new__(cls, *args, **kwargs): """ Create a new dimension. Possibilities are (examples given with list/tuple work also with tuple/list): >>> from sympy.physics.unitsystems.dimensions import Dimension >>> Dimension(length=1) {'length': 1} >>> Dimension({"length": 1}) {'length': 1} >>> Dimension([("length", 1), ("time", -1)]) #doctest: +SKIP {'length': 1, 'time': -1} """ # before setting the dict, check if a name and/or a symbol are defined # if so, remove them from the dict name = kwargs.pop('name', None) symbol = kwargs.pop('symbol', None) # pairs of (dimension, power) pairs = [] # add first items from args to the pairs for arg in args: # construction with {"length": 1} if isinstance(arg, dict): arg = copy(arg) pairs.extend(arg.items()) elif isinstance(arg, (Tuple, tuple, list)): #TODO: add construction with ("length", 1); not trivial because # e.g. [("length", 1), ("time", -1)] has also length = 2 for p in arg: #TODO: check that p is a tuple if len(p) != 2: raise ValueError("Length of iterable has to be 2; " "'%d' found" % len(p)) # construction with [("length", 1), ...] pairs.extend(arg) else: # error if the arg is not of previous types raise TypeError("Positional arguments can only be: " "dict, tuple, list; '%s' found" % type(arg)) pairs.extend(kwargs.items()) # check validity of dimension key and power for pair in pairs: #if not isinstance(p[0], str): # raise TypeError("key %s is not a string." % p[0]) if not isinstance(pair[1], (numbers.Real, Number)): raise TypeError("Power corresponding to '%s' is not a number" % pair[0]) # filter dimensions set to zero; this avoid the following odd result: # Dimension(length=1) == Dimension(length=1, mass=0) => False # also simplify to avoid powers such as 2.00000 pairs = [(pair[0], nsimplify(pair[1])) for pair in pairs if pair[1] != 0] pairs.sort(key=str) new = Expr.__new__(cls, Dict(*pairs)) new.name = name new.symbol = symbol new._dict = dict(pairs) return new
def density(self): return Dict(self._density)
def parse_dict(d): return Dict({parse_dim_name(i): j for i, j in d.items()})
def __new__(cls, base_dims, derived_dims=(), dimensional_dependencies={}): dimensional_dependencies = dict(dimensional_dependencies) def parse_dim(dim): if isinstance(dim, str): dim = Dimension(Symbol(dim)) elif isinstance(dim, Dimension): pass elif isinstance(dim, Symbol): dim = Dimension(dim) else: raise TypeError("%s wrong type" % dim) return dim base_dims = [parse_dim(i) for i in base_dims] derived_dims = [parse_dim(i) for i in derived_dims] for dim in base_dims: dim = dim.name if (dim in dimensional_dependencies and (len(dimensional_dependencies[dim]) != 1 or dimensional_dependencies[dim].get(dim, None) != 1)): raise IndexError("Repeated value in base dimensions") dimensional_dependencies[dim] = Dict({dim: 1}) def parse_dim_name(dim): if isinstance(dim, Dimension): return dim.name elif isinstance(dim, str): return Symbol(dim) elif isinstance(dim, Symbol): return dim else: raise TypeError("unrecognized type %s for %s" % (type(dim), dim)) for dim in dimensional_dependencies.keys(): dim = parse_dim(dim) if (dim not in derived_dims) and (dim not in base_dims): derived_dims.append(dim) def parse_dict(d): return Dict({parse_dim_name(i): j for i, j in d.items()}) # Make sure everything is a SymPy type: dimensional_dependencies = { parse_dim_name(i): parse_dict(j) for i, j in dimensional_dependencies.items() } for dim in derived_dims: if dim in base_dims: raise ValueError("Dimension %s both in base and derived" % dim) if dim.name not in dimensional_dependencies: # TODO: should this raise a warning? dimensional_dependencies[dim.name] = Dict({dim.name: 1}) base_dims.sort(key=default_sort_key) derived_dims.sort(key=default_sort_key) base_dims = Tuple(*base_dims) derived_dims = Tuple(*derived_dims) dimensional_dependencies = Dict( {i: Dict(j) for i, j in dimensional_dependencies.items()}) obj = Basic.__new__(cls, base_dims, derived_dims, dimensional_dependencies) return obj
def test_factorint(): assert primefactors(123456) == [2, 3, 643] assert factorint(0) == {0: 1} assert factorint(1) == {} assert factorint(-1) == {-1: 1} assert factorint(-2) == {-1: 1, 2: 1} assert factorint(-16) == {-1: 1, 2: 4} assert factorint(2) == {2: 1} assert factorint(126) == {2: 1, 3: 2, 7: 1} assert factorint(123456) == {2: 6, 3: 1, 643: 1} assert factorint(5951757) == {3: 1, 7: 1, 29: 2, 337: 1} assert factorint(64015937) == {7993: 1, 8009: 1} assert factorint(2**(2**6) + 1) == {274177: 1, 67280421310721: 1} #issue 19683 assert factorint(10**38 - 1) == { 3: 2, 11: 1, 909090909090909091: 1, 1111111111111111111: 1 } #issue 17676 assert factorint(28300421052393658575) == { 3: 1, 5: 2, 11: 2, 43: 1, 2063: 2, 4127: 1, 4129: 1 } assert factorint(2063**2 * 4127**1 * 4129**1) == { 2063: 2, 4127: 1, 4129: 1 } assert factorint(2347**2 * 7039**1 * 7043**1) == { 2347: 2, 7039: 1, 7043: 1 } assert factorint(0, multiple=True) == [0] assert factorint(1, multiple=True) == [] assert factorint(-1, multiple=True) == [-1] assert factorint(-2, multiple=True) == [-1, 2] assert factorint(-16, multiple=True) == [-1, 2, 2, 2, 2] assert factorint(2, multiple=True) == [2] assert factorint(24, multiple=True) == [2, 2, 2, 3] assert factorint(126, multiple=True) == [2, 3, 3, 7] assert factorint(123456, multiple=True) == [2, 2, 2, 2, 2, 2, 3, 643] assert factorint(5951757, multiple=True) == [3, 7, 29, 29, 337] assert factorint(64015937, multiple=True) == [7993, 8009] assert factorint(2**(2**6) + 1, multiple=True) == [274177, 67280421310721] assert factorint(fac(1, evaluate=False)) == {} assert factorint(fac(7, evaluate=False)) == {2: 4, 3: 2, 5: 1, 7: 1} assert factorint(fac(15, evaluate=False)) == \ {2: 11, 3: 6, 5: 3, 7: 2, 11: 1, 13: 1} assert factorint(fac(20, evaluate=False)) == \ {2: 18, 3: 8, 5: 4, 7: 2, 11: 1, 13: 1, 17: 1, 19: 1} assert factorint(fac(23, evaluate=False)) == \ {2: 19, 3: 9, 5: 4, 7: 3, 11: 2, 13: 1, 17: 1, 19: 1, 23: 1} assert multiproduct(factorint(fac(200))) == fac(200) assert multiproduct(factorint(fac(200, evaluate=False))) == fac(200) for b, e in factorint(fac(150)).items(): assert e == fac_multiplicity(150, b) for b, e in factorint(fac(150, evaluate=False)).items(): assert e == fac_multiplicity(150, b) assert factorint(103005006059**7) == {103005006059: 7} assert factorint(31337**191) == {31337: 191} assert factorint(2**1000 * 3**500 * 257**127 * 383**60) == \ {2: 1000, 3: 500, 257: 127, 383: 60} assert len(factorint(fac(10000))) == 1229 assert len(factorint(fac(10000, evaluate=False))) == 1229 assert factorint(12932983746293756928584532764589230) == \ {2: 1, 5: 1, 73: 1, 727719592270351: 1, 63564265087747: 1, 383: 1} assert factorint(727719592270351) == {727719592270351: 1} assert factorint(2**64 + 1, use_trial=False) == factorint(2**64 + 1) for n in range(60000): assert multiproduct(factorint(n)) == n assert pollard_rho(2**64 + 1, seed=1) == 274177 assert pollard_rho(19, seed=1) is None assert factorint(3, limit=2) == {3: 1} assert factorint(12345) == {3: 1, 5: 1, 823: 1} assert factorint(12345, limit=3) == { 4115: 1, 3: 1 } # the 5 is greater than the limit assert factorint(1, limit=1) == {} assert factorint(0, 3) == {0: 1} assert factorint(12, limit=1) == {12: 1} assert factorint(30, limit=2) == {2: 1, 15: 1} assert factorint(16, limit=2) == {2: 4} assert factorint(124, limit=3) == {2: 2, 31: 1} assert factorint(4 * 31**2, limit=3) == {2: 2, 31: 2} p1 = nextprime(2**32) p2 = nextprime(2**16) p3 = nextprime(p2) assert factorint(p1 * p2 * p3) == {p1: 1, p2: 1, p3: 1} assert factorint(13 * 17 * 19, limit=15) == {13: 1, 17 * 19: 1} assert factorint(1951 * 15013 * 15053, limit=2000) == { 225990689: 1, 1951: 1 } assert factorint(primorial(17) + 1, use_pm1=0) == \ {int(19026377261): 1, 3467: 1, 277: 1, 105229: 1} # when prime b is closer than approx sqrt(8*p) to prime p then they are # "close" and have a trivial factorization a = nextprime(2**2**8) # 78 digits b = nextprime(a + 2**2**4) assert 'Fermat' in capture(lambda: factorint(a * b, verbose=1)) raises(ValueError, lambda: pollard_rho(4)) raises(ValueError, lambda: pollard_pm1(3)) raises(ValueError, lambda: pollard_pm1(10, B=2)) # verbose coverage n = nextprime(2**16) * nextprime(2**17) * nextprime(1901) assert 'with primes' in capture(lambda: factorint(n, verbose=1)) capture(lambda: factorint(nextprime(2**16) * 1012, verbose=1)) n = nextprime(2**17) capture(lambda: factorint(n**3, verbose=1)) # perfect power termination capture(lambda: factorint(2 * n, verbose=1)) # factoring complete msg # exceed 1st n = nextprime(2**17) n *= nextprime(n) assert '1000' in capture(lambda: factorint(n, limit=1000, verbose=1)) n *= nextprime(n) assert len(factorint(n)) == 3 assert len(factorint(n, limit=p1)) == 3 n *= nextprime(2 * n) # exceed 2nd assert '2001' in capture(lambda: factorint(n, limit=2000, verbose=1)) assert capture(lambda: factorint(n, limit=4000, verbose=1)).count( 'Pollard') == 2 # non-prime pm1 result n = nextprime(8069) n *= nextprime(2 * n) * nextprime(2 * n, 2) capture(lambda: factorint(n, verbose=1)) # non-prime pm1 result # factor fermat composite p1 = nextprime(2**17) p2 = nextprime(2 * p1) assert factorint((p1 * p2**2)**3) == {p1: 3, p2: 6} # Test for non integer input raises(ValueError, lambda: factorint(4.5)) # test dict/Dict input sans = '2**10*3**3' n = {4: 2, 12: 3} assert str(factorint(n)) == sans assert str(factorint(Dict(n))) == sans
def dict(self): return FiniteSet(*[Dict(dict(el)) for el in self.elements])
def test_ndim_array_initiation(): arr_with_no_elements = ImmutableDenseNDimArray([], shape=(0, )) assert len(arr_with_no_elements) == 0 assert arr_with_no_elements.rank() == 1 raises(ValueError, lambda: ImmutableDenseNDimArray([0], shape=(0, ))) raises(ValueError, lambda: ImmutableDenseNDimArray([1, 2, 3], shape=(0, ))) raises(ValueError, lambda: ImmutableDenseNDimArray([], shape=())) raises(ValueError, lambda: ImmutableSparseNDimArray([0], shape=(0, ))) raises(ValueError, lambda: ImmutableSparseNDimArray([1, 2, 3], shape=(0, ))) raises(ValueError, lambda: ImmutableSparseNDimArray([], shape=())) arr_with_one_element = ImmutableDenseNDimArray([23]) assert len(arr_with_one_element) == 1 assert arr_with_one_element[0] == 23 assert arr_with_one_element[:] == ImmutableDenseNDimArray([23]) assert arr_with_one_element.rank() == 1 arr_with_symbol_element = ImmutableDenseNDimArray([Symbol('x')]) assert len(arr_with_symbol_element) == 1 assert arr_with_symbol_element[0] == Symbol('x') assert arr_with_symbol_element[:] == ImmutableDenseNDimArray([Symbol('x')]) assert arr_with_symbol_element.rank() == 1 number5 = 5 vector = ImmutableDenseNDimArray.zeros(number5) assert len(vector) == number5 assert vector.shape == (number5, ) assert vector.rank() == 1 vector = ImmutableSparseNDimArray.zeros(number5) assert len(vector) == number5 assert vector.shape == (number5, ) assert vector._sparse_array == Dict() assert vector.rank() == 1 n_dim_array = ImmutableDenseNDimArray(range(3**4), ( 3, 3, 3, 3, )) assert len(n_dim_array) == 3 * 3 * 3 * 3 assert n_dim_array.shape == (3, 3, 3, 3) assert n_dim_array.rank() == 4 array_shape = (3, 3, 3, 3) sparse_array = ImmutableSparseNDimArray.zeros(*array_shape) assert len(sparse_array._sparse_array) == 0 assert len(sparse_array) == 3 * 3 * 3 * 3 assert n_dim_array.shape == array_shape assert n_dim_array.rank() == 4 one_dim_array = ImmutableDenseNDimArray([2, 3, 1]) assert len(one_dim_array) == 3 assert one_dim_array.shape == (3, ) assert one_dim_array.rank() == 1 assert one_dim_array.tolist() == [2, 3, 1] shape = (3, 3) array_with_many_args = ImmutableSparseNDimArray.zeros(*shape) assert len(array_with_many_args) == 3 * 3 assert array_with_many_args.shape == shape assert array_with_many_args[0, 0] == 0 assert array_with_many_args.rank() == 2 shape = (int(3), int(3)) array_with_long_shape = ImmutableSparseNDimArray.zeros(*shape) assert len(array_with_long_shape) == 3 * 3 assert array_with_long_shape.shape == shape assert array_with_long_shape[int(0), int(0)] == 0 assert array_with_long_shape.rank() == 2 vector_with_long_shape = ImmutableDenseNDimArray(range(5), int(5)) assert len(vector_with_long_shape) == 5 assert vector_with_long_shape.shape == (int(5), ) assert vector_with_long_shape.rank() == 1 raises(ValueError, lambda: vector_with_long_shape[int(5)]) from sympy.abc import x for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]: rank_zero_array = ArrayType(x) assert len(rank_zero_array) == 1 assert rank_zero_array.shape == () assert rank_zero_array.rank() == 0 assert rank_zero_array[()] == x raises(ValueError, lambda: rank_zero_array[0])