Integer comparison with string question

24 views
Skip to first unread message

Mariah Lenox

unread,
Mar 21, 2012, 1:10:49 PM3/21/12
to sage-s...@googlegroups.com
python: 1 < 'haha'
true

sage: 1 < 'haha'
false

Ok, python and sage do something different. Why?

sage: preparse('1 < "haha"')
'Integer(1) < "haha"

And here I am stuck. I have looked through the sage reference manual, and tried
googling, but no luck.

Would a kind person explain why python and sage give different answers?

Mariah

William Stein

unread,
Mar 21, 2012, 1:16:19 PM3/21/12
to sage-s...@googlegroups.com

They give different answers because a = Integer(1) and b = int(1) have
a different definition of __richcmp__. Sage tries to canonically
coerce the inputs to a common parent:

sage: canonical_coercion(Integer(1), 'haha')
...
TypeError

and fails, so it compares their types (copied from element.pyx):

except (TypeError, NotImplementedError):
r = cmp(type(left), type(right))
if r == 0:
r = -1


sage: cmp(type(Integer(1)), type('haha'))
1

so

sage: type(Integer(1))< type('haha')
False

Python ints, on the other hand, evidently implement their __richcmp__
differently. To figure out how, you'll probably have to look at the
source code of the Python interpreter.

William

>
> Mariah
>
> --
> To post to this group, send email to sage-s...@googlegroups.com
> To unsubscribe from this group, send email to sage-support...@googlegroups.com
> For more options, visit this group at http://groups.google.com/group/sage-support
> URL: http://www.sagemath.org

--
William Stein
Professor of Mathematics
University of Washington
http://wstein.org

Reply all
Reply to author
Forward
0 new messages