Confusing problem (well, for me anyway)
Duncan Smith
buzzard at urubu.freeserve.co.uk
Sat Feb 22 14:03:50 EST 2003
I cannot see what I am doing wrong here. The following function won't make
a great deal of sense on its own, but I'm hoping my error is obvious enough
that that won't matter. The output below the function highlights the
problem.
def __cmp__(self, other):
indices = []
for variable in other.variables:
indices.append(self.variables.index(variable))
try:
self.transpose(indices)
except:
return 0
if self.variables == other.variables:
array1, array2 = self.values, other.values
##########################################
comp = array1 == array2
for i in range(len(array1.shape)):
comp = Numeric.add.reduce(comp)
size = Numeric.multiply.reduce(array1.shape)
print comp, size, comp == size
if comp == size:
print 'returning 1'
return 1
else:
print 'returning 0'
return 0
###########################################
else:
return 0
>>> reload(disc)
<module 'disc' from 'C:\Python22\disc.pyc'>
>>> t = disc.RandomTable(0, 6, [2,3])
>>> t1 = t.copy()
>>> t
array([[4, 4, 3],
[2, 3, 4]]) ['var1', 'var2']
>>> t1
array([[4, 4, 3],
[2, 3, 4]]) ['var1', 'var2']
>>> t == t1
6 6 1
returning 1
0
>>> t.values[(0,0)] = 5
>>> t == t1
5 6 0
returning 0
1
>>> t.values[(0,0)] = 4
>>> t == t1
6 6 1
returning 1
0
>>>
I cannot see why the function returns 1 when it should return 0 (and
vice-versa). How can it print 'returning 1' and then return 0? If I place
the code between the lines of hashes in a separate function and pass it two
Numeric arrays as arguments I get the behaviour I'd expect.
def equals(array1, array2):
comp = array1 == array2
for i in range(len(array1.shape)):
comp = Numeric.add.reduce(comp)
size = Numeric.multiply.reduce(array1.shape)
if comp == size:
print 'returning 1'
return 1
else:
print 'returning 0'
return 0
>>> disc.equals(array1, array2)
returning 1
1
But if I replace the section of code with 'return equals(array1, array2)',
then I'm back to the 'strange' behaviour. Any ideas? Cheers.
Duncan
More information about the Python-list
mailing list