equivalent of NULL or OM in Python

Steve Holden sholden at holdenweb.com
Fri Feb 16 09:40:47 EST 2001


--
Tools, training and technology to help you meet your information needs



"cyberian bear" <cyberian_bear at hotmail.com> wrote in message
news:2G5j6.1$CF4.251 at typhoon.nyu.edu...
> 1.I'm doing a program in Python which perform +, -, *, / on two
polynomials.
> Their coefficient and exponentials are stored in tuples. So for example
> 3X^2+4X+4 would be stored like [(2,3),(1,4),(0,4)] but what if the term is
> absent completely from one of the polynomials then i would have to check
if
> one of the tuuples is not present at all and not just zero. For  example
> [(2,3),(0,4)]. In Pascal there is NULL in SETL there is OM but is there a
> corresponding statement in Python. I've checked through several sources
> including my textbook but didn't find the satisfactory answer. Maybe I
> should just check if the second term of every tuple(i.e the coefficient)
is
> zero which means that the term is not present.

Choice of data representation can be critical in algorithm design, and this
is quite a good example. However, I have not fully considered the symbolic
manipulations you want to perform, so I may be putting my foot in my mouth
here. That's how I know I have a size 10 mouth: the foot fits perfectly.

It would appear to be more regular to represent absent terms as a
coefficient of zero. Furthermore, if you reverse the order of the terms,
putting x^0 at the left, you can then use the index into the list as the
power. So your examples could be represented as follows:

3X^2+4X+4 : [4, 4, 3]
3x^2+4: [4, 0, 3]

Evaluation for a particular value of x then comes down to:

>>> poly = [4, 4, 3]
>>> r = 0
>>> x = 2
>>> for p in range(len(poly)):
...  r = r + (x^p)*poly[p]
...
>>> r
20

Polynomial addition would just add the equivalent coefficients (although you
would need to extend the shorter woth zeroes to make them equal lengths).
The rest is left as an exercise :-)

Would this representation be more tractable?

> 2. Also can anyone give me a clue how to iterate over all the coefficient
> terms in the tuples in the first polynomials' tuples.
> My guess is should be something like
> for coefficient in polynomial1:
> where polynomial is a list of tuples
> but how do i tell it to iterate specifically over the second term in every
> tuple and not over the whole tuples
> cb
>
>
Using your representation, what you want is something like:

>>> poly = [(2,3),(1,4),(0,4)]
>>> for i, c in poly:
...  print "Index:", i, "Coefficient:", c
...
Index: 2 Coefficient: 3
Index: 1 Coefficient: 4
Index: 0 Coefficient: 4

Obviously you can ignore the indexes if you want...

Does any of this help?

regards
 Steve





More information about the Python-list mailing list