Kay Schluehr wrote:
> Here might be an interesting puzzle for people who like sorting
> algorithms ( and no I'm not a student anymore and the problem is not a
> students 'homework' but a particular question associated with a
> computer algebra system in Python I'm currently developing in my
> sparetime ).
> For motivation lets define some expression class first:
This works for (simple) expressions with mixed multiplication and addition.
def __add__(self, other):
def __radd__(self, other):
def __mul__(self, other):
def __rmul__(self, other):
for i in self:
if isinstance(i,A) \
def __init__(self, *x):
return "+".join([str(x) for x in self])
return "*".join([str(x) for x in self])
a = F('a')
b = F('b')
c = F('c')
d = F('d')
print '\n a =', a
print '\n b+a+2 =', b+a+2
print '\n c*b+d*a+2 =', c*b+d*a+2
print '\n 7*a*8*9+b =', 7*a*8*9+b
a = a
b+a+2 = 2+a+b
c*b+d*a+2 = 2+a*d+b*c
7*a*8*9+b = 9*8*7*a+b <-- reverse sorted digits?
The digits sort in reverse for some strange reason I haven't figured out
yet, but they are grouped together. And expressions of the type a*(c+b)
don't work in this example.
It probably needs some better logic to merge adjacent like groups. I
think the reverse sorting my be a side effect of the nesting that takes
place when the expressions are built.
Having the digits first might be an advantage as you can use a for loop
to add or multiply them until you get to a not digit.
Anyway, interesting stuff. ;-)