10 Hash of a sequence, that *depends* on the order of elements.
12 # make this more robust:
15 m
= hash(m
+ 1001 ^
hash(x
))
20 def __new__(cls
, type, args
):
21 obj
= object.__new
__(cls
)
23 obj
._args
= tuple(args
)
31 if self
.mhash
is None:
32 h
= hash_seq(self
.args
)
42 def as_coeff_rest(self
):
43 return (Integer(1), self
)
45 def as_base_exp(self
):
46 return (self
, Integer(1))
70 return Mul((x
, Pow((y
, Integer(-1)))))
73 return Mul((y
, Pow((x
, Integer(-1)))))
82 return Mul((Integer(-1), x
))
88 return not self
.__eq
__(x
)
92 if o
.type == self
.type:
93 return self
.args
== o
.args
101 obj
= Basic
.__new
__(cls
, INTEGER
, [])
106 if self
.mhash
is None:
115 if o
.type == INTEGER
:
123 def __add__(self
, o
):
125 if o
.type == INTEGER
:
126 return Integer(self
.i
+o
.i
)
127 return Basic
.__add
__(self
, o
)
129 def __mul__(self
, o
):
131 if o
.type == INTEGER
:
132 return Integer(self
.i
*o
.i
)
133 return Basic
.__mul
__(self
, o
)
138 def __new__(cls
, name
):
139 obj
= Basic
.__new
__(cls
, SYMBOL
, [])
144 if self
.mhash
is None:
154 return self
.name
== o
.name
163 def __new__(cls
, args
, canonicalize
=True):
164 if canonicalize
== False:
165 obj
= Basic
.__new
__(cls
, ADD
, args
)
168 args
= [sympify(x
) for x
in args
]
169 return Add
.canonicalize(args
)
172 def canonicalize(cls
, args
):
175 from csympy
import HashTable
181 if a
.type == INTEGER
:
185 if b
.type == INTEGER
:
188 coeff
, key
= b
.as_coeff_rest()
194 coeff
, key
= a
.as_coeff_rest()
202 for a
, b
in d
.iteritems():
203 args
.append(Mul((a
, b
)))
209 return Add(args
, False)
211 def freeze_args(self
):
212 #print "add is freezing"
213 if self
._args
_set
is None:
214 self
._args
_set
= frozenset(self
.args
)
222 return self
._args
_set
== o
._args
_set
227 s
= str(self
.args
[0])
228 if self
.args
[0].type == ADD
:
230 for x
in self
.args
[1:]:
231 s
= "%s + %s" % (s
, str(x
))
237 if self
.mhash
is None:
238 # XXX: it is surprising, but this is *not* faster:
240 #h = hash(self._args_set)
243 a
= list(self
.args
[:])
253 for term
in self
.args
:
254 r
.append( term
.expand() )
259 def __new__(cls
, args
, canonicalize
=True):
260 if canonicalize
== False:
261 obj
= Basic
.__new
__(cls
, MUL
, args
)
264 args
= [sympify(x
) for x
in args
]
265 return Mul
.canonicalize(args
)
268 def canonicalize(cls
, args
):
271 from csympy
import HashTable
277 if a
.type == INTEGER
:
281 if b
.type == INTEGER
:
284 key
, coeff
= b
.as_base_exp()
290 key
, coeff
= a
.as_base_exp()
295 if num
.i
== 0 or len(d
)==0:
298 for a
, b
in d
.iteritems():
299 args
.append(Pow((a
, b
)))
305 return Mul(args
, False)
308 if self
.mhash
is None:
309 # in contrast to Add, here it is faster:
311 h
= hash(self
._args
_set
)
313 #a = list(self.args[:])
321 def freeze_args(self
):
322 #print "mul is freezing"
323 if self
._args
_set
is None:
324 self
._args
_set
= frozenset(self
.args
)
332 return self
._args
_set
== o
._args
_set
337 def as_coeff_rest(self
):
338 if self
.args
[0].type == INTEGER
:
339 return self
.as_two_terms()
340 return (Integer(1), self
)
342 def as_two_terms(self
):
349 return (a0
, Mul(args
[1:], False))
353 s
= str(self
.args
[0])
354 if self
.args
[0].type in [ADD
, MUL
]:
356 for x
in self
.args
[1:]:
357 if x
.type in [ADD
, MUL
]:
358 s
= "%s * (%s)" % (s
, str(x
))
360 s
= "%s*%s" % (s
, str(x
))
364 def expand_two(self
, a
, b
):
366 Both a and b are assumed to be expanded.
368 if a
.type == ADD
and b
.type == ADD
:
387 a
, b
= self
.as_two_terms()
388 r
= Mul
.expand_two(a
, b
)
392 return Mul
.expand_two(a
, b
)
398 def __new__(cls
, args
, canonicalize
=True):
399 if canonicalize
== False:
400 obj
= Basic
.__new
__(cls
, POW
, args
)
402 args
= [sympify(x
) for x
in args
]
403 return Pow
.canonicalize(args
)
406 def canonicalize(cls
, args
):
408 if base
.type == INTEGER
:
413 if exp
.type == INTEGER
:
419 return Pow((base
.args
[0], base
.args
[1]*exp
))
420 return Pow(args
, False)
423 s
= str(self
.args
[0])
424 if self
.args
[0].type == ADD
:
426 if self
.args
[1].type == ADD
:
427 s
= "%s^(%s)" % (s
, str(self
.args
[1]))
429 s
= "%s^%s" % (s
, str(self
.args
[1]))
432 def as_base_exp(self
):
436 base
, exp
= self
.args
437 if base
.type == ADD
and exp
.type == INTEGER
:
441 d
= multinomial_coefficients(m
, n
)
444 for powers
, coeff
in d
.iteritems():
449 for x
, p
in zip(base
.args
, powers
):
451 t
.append(Pow((x
, p
)))
464 if isinstance(x
, int):
470 Create a symbolic variable with the name *s*.
473 s -- a string, either a single variable name, or
474 a space separated list of variable names, or
475 a list of variable names.
477 NOTE: The new variable is both returned and automatically injected into
478 the parent's *global* namespace. It's recommended not to use "var" in
479 library code, it is better to use symbols() instead.
482 We define some symbolic variables:
485 >>> var('n xx yy zz')
493 frame
= inspect
.currentframe().f_back
496 if not isinstance(s
, list):
497 s
= re
.split('\s|,', s
)
506 frame
.f_globals
[t
] = sym
510 if len(res
) == 0: # var('')
512 elif len(res
) == 1: # var('x')
514 # otherwise var('a b ...')
518 # we should explicitly break cyclic dependencies as stated in inspect
522 def binomial_coefficients(n
):
523 """Return a dictionary containing pairs {(k1,k2) : C_kn} where
524 C_kn are binomial coefficients and n=k1+k2."""
525 d
= {(0, n
):1, (n
, 0):1}
527 for k
in xrange(1, n
//2+1):
529 d
[k
, n
-k
] = d
[n
-k
, k
] = a
532 def binomial_coefficients_list(n
):
533 """ Return a list of binomial coefficients as rows of the Pascal's
538 for k
in xrange(1, n
//2+1):
543 def multinomial_coefficients(m
, n
, _tuple
=tuple, _zip
=zip):
544 """Return a dictionary containing pairs ``{(k1,k2,..,km) : C_kn}``
545 where ``C_kn`` are multinomial coefficients such that
550 >>> print multinomial_coefficients(2,5)
551 {(3, 2): 10, (1, 4): 5, (2, 3): 10, (5, 0): 1, (0, 5): 1, (4, 1): 5}
553 The algorithm is based on the following result:
555 Consider a polynomial and it's ``m``-th exponent::
557 P(x) = sum_{i=0}^m p_i x^k
558 P(x)^n = sum_{k=0}^{m n} a(n,k) x^k
560 The coefficients ``a(n,k)`` can be computed using the
561 J.C.P. Miller Pure Recurrence [see D.E.Knuth, Seminumerical
562 Algorithms, The art of Computer Programming v.2, Addison
563 Wesley, Reading, 1981;]::
565 a(n,k) = 1/(k p_0) sum_{i=1}^m p_i ((n+1)i-k) a(n,k-i),
567 where ``a(n,0) = p_0^n``.
571 return binomial_coefficients(n
)
572 symbols
= [(0,)*i
+ (1,) + (0,)*(m
-i
-1) for i
in range(m
)]
574 p0
= [_tuple(aa
-bb
for aa
,bb
in _zip(s
,s0
)) for s
in symbols
]
575 r
= {_tuple(aa
*n
for aa
in s0
):1}
578 l
= [0] * (n
*(m
-1)+1)
580 for k
in xrange(1, n
*(m
-1)+1):
583 for i
in xrange(1, min(m
,k
+1)):
588 for t2
, c2
in l
[k
-i
]:
589 tt
= _tuple([aa
+bb
for aa
,bb
in _zip(t2
,t
)])
600 r1
= [(t
, c
//k
) for (t
, c
) in d
.iteritems()]