10 Hash of a sequence, that *depends* on the order of elements.
12 # make this more robust:
15 m
= hash(m
+ 1001 ^
hash(x
))
18 def compare_lists(a
, b
):
20 Compare two sequences.
22 Sequences are equal even with a *different* order of elements.
25 return set(a
) == set(b
)
29 def __new__(cls
, type, args
):
30 obj
= object.__new
__(cls
)
32 obj
._args
= tuple(args
)
39 return hash_seq(self
.args
)
45 def as_coeff_rest(self
):
46 return (Integer(1), self
)
48 def as_base_exp(self
):
49 return (self
, Integer(1))
73 return Mul((x
, Pow((y
, Integer(-1)))))
76 return Mul((y
, Pow((x
, Integer(-1)))))
85 return Mul((Integer(-1), x
))
91 return not self
.__eq
__(x
)
95 if o
.type == self
.type:
96 return self
.args
== o
.args
101 class Integer(Basic
):
104 obj
= Basic
.__new
__(cls
, INTEGER
, [])
113 if o
.type == INTEGER
:
121 def __add__(self
, o
):
123 if o
.type == INTEGER
:
124 return Integer(self
.i
+o
.i
)
125 return Basic
.__add
__(self
, o
)
127 def __mul__(self
, o
):
129 if o
.type == INTEGER
:
130 return Integer(self
.i
*o
.i
)
131 return Basic
.__mul
__(self
, o
)
136 def __new__(cls
, name
):
137 obj
= Basic
.__new
__(cls
, SYMBOL
, [])
142 return hash(self
.name
)
147 return self
.name
== o
.name
156 def __new__(cls
, args
, canonicalize
=True):
157 if canonicalize
== False:
158 obj
= Basic
.__new
__(cls
, ADD
, args
)
160 args
= [sympify(x
) for x
in args
]
161 return Add
.canonicalize(args
)
164 def canonicalize(cls
, args
):
167 from csympy
import HashTable
173 if a
.type == INTEGER
:
177 if b
.type == INTEGER
:
180 coeff
, key
= b
.as_coeff_rest()
186 coeff
, key
= a
.as_coeff_rest()
194 for a
, b
in d
.iteritems():
195 args
.append(Mul((a
, b
)))
201 return Add(args
, False)
206 return compare_lists(self
.args
, o
.args
)
211 s
= str(self
.args
[0])
212 if self
.args
[0].type == ADD
:
214 for x
in self
.args
[1:]:
215 s
= "%s + %s" % (s
, str(x
))
221 a
= list(self
.args
[:])
227 for term
in self
.args
:
233 def __new__(cls
, args
, canonicalize
=True):
234 if canonicalize
== False:
235 obj
= Basic
.__new
__(cls
, MUL
, args
)
237 args
= [sympify(x
) for x
in args
]
238 return Mul
.canonicalize(args
)
241 def canonicalize(cls
, args
):
244 from csympy
import HashTable
250 if a
.type == INTEGER
:
254 if b
.type == INTEGER
:
257 key
, coeff
= b
.as_base_exp()
263 key
, coeff
= a
.as_base_exp()
268 if num
.i
== 0 or len(d
)==0:
271 for a
, b
in d
.iteritems():
272 args
.append(Pow((a
, b
)))
278 return Mul(args
, False)
281 a
= list(self
.args
[:])
288 return compare_lists(self
.args
, o
.args
)
293 def as_coeff_rest(self
):
294 if self
.args
[0].type == INTEGER
:
295 return self
.as_two_terms()
296 return (Integer(1), self
)
298 def as_two_terms(self
):
299 return (self
.args
[0], Mul(self
.args
[1:]))
303 s
= str(self
.args
[0])
304 if self
.args
[0].type in [ADD
, MUL
]:
306 for x
in self
.args
[1:]:
307 if x
.type in [ADD
, MUL
]:
308 s
= "%s * (%s)" % (s
, str(x
))
310 s
= "%s*%s" % (s
, str(x
))
314 def expand_two(self
, a
, b
):
316 Both a and b are assumed to be expanded.
318 if a
.type == ADD
and b
.type == ADD
:
337 a
, b
= self
.as_two_terms()
338 r
= Mul
.expand_two(a
, b
)
342 return Mul
.expand_two(a
, b
)
348 def __new__(cls
, args
, canonicalize
=True):
349 if canonicalize
== False:
350 obj
= Basic
.__new
__(cls
, POW
, args
)
352 args
= [sympify(x
) for x
in args
]
353 return Pow
.canonicalize(args
)
356 def canonicalize(cls
, args
):
358 if base
.type == INTEGER
:
363 if exp
.type == INTEGER
:
369 return Pow((base
.args
[0], base
.args
[1]*exp
))
370 return Pow(args
, False)
373 s
= str(self
.args
[0])
374 if self
.args
[0].type == ADD
:
376 if self
.args
[1].type == ADD
:
377 s
= "%s^(%s)" % (s
, str(self
.args
[1]))
379 s
= "%s^%s" % (s
, str(self
.args
[1]))
382 def as_base_exp(self
):
386 base
, exp
= self
.args
387 if base
.type == ADD
and exp
.type == INTEGER
:
390 d
= multinomial_coefficients(m
, n
)
392 for powers
, coeff
in d
.iteritems():
394 for x
, p
in zip(base
.args
, powers
):
401 if isinstance(x
, int):
407 Create a symbolic variable with the name *s*.
410 s -- a string, either a single variable name, or
411 a space separated list of variable names, or
412 a list of variable names.
414 NOTE: The new variable is both returned and automatically injected into
415 the parent's *global* namespace. It's recommended not to use "var" in
416 library code, it is better to use symbols() instead.
419 We define some symbolic variables:
422 >>> var('n xx yy zz')
430 frame
= inspect
.currentframe().f_back
433 if not isinstance(s
, list):
434 s
= re
.split('\s|,', s
)
443 frame
.f_globals
[t
] = sym
447 if len(res
) == 0: # var('')
449 elif len(res
) == 1: # var('x')
451 # otherwise var('a b ...')
455 # we should explicitly break cyclic dependencies as stated in inspect
459 def binomial_coefficients(n
):
460 """Return a dictionary containing pairs {(k1,k2) : C_kn} where
461 C_kn are binomial coefficients and n=k1+k2."""
462 d
= {(0, n
):1, (n
, 0):1}
464 for k
in xrange(1, n
//2+1):
466 d
[k
, n
-k
] = d
[n
-k
, k
] = a
469 def binomial_coefficients_list(n
):
470 """ Return a list of binomial coefficients as rows of the Pascal's
475 for k
in xrange(1, n
//2+1):
480 def multinomial_coefficients(m
, n
, _tuple
=tuple, _zip
=zip):
481 """Return a dictionary containing pairs ``{(k1,k2,..,km) : C_kn}``
482 where ``C_kn`` are multinomial coefficients such that
487 >>> print multinomial_coefficients(2,5)
488 {(3, 2): 10, (1, 4): 5, (2, 3): 10, (5, 0): 1, (0, 5): 1, (4, 1): 5}
490 The algorithm is based on the following result:
492 Consider a polynomial and it's ``m``-th exponent::
494 P(x) = sum_{i=0}^m p_i x^k
495 P(x)^n = sum_{k=0}^{m n} a(n,k) x^k
497 The coefficients ``a(n,k)`` can be computed using the
498 J.C.P. Miller Pure Recurrence [see D.E.Knuth, Seminumerical
499 Algorithms, The art of Computer Programming v.2, Addison
500 Wesley, Reading, 1981;]::
502 a(n,k) = 1/(k p_0) sum_{i=1}^m p_i ((n+1)i-k) a(n,k-i),
504 where ``a(n,0) = p_0^n``.
508 return binomial_coefficients(n
)
509 symbols
= [(0,)*i
+ (1,) + (0,)*(m
-i
-1) for i
in range(m
)]
511 p0
= [_tuple(aa
-bb
for aa
,bb
in _zip(s
,s0
)) for s
in symbols
]
512 r
= {_tuple(aa
*n
for aa
in s0
):1}
515 l
= [0] * (n
*(m
-1)+1)
517 for k
in xrange(1, n
*(m
-1)+1):
520 for i
in xrange(1, min(m
,k
+1)):
525 for t2
, c2
in l
[k
-i
]:
526 tt
= _tuple([aa
+bb
for aa
,bb
in _zip(t2
,t
)])
537 r1
= [(t
, c
//k
) for (t
, c
) in d
.iteritems()]