fraction in nested list comprehension

22 views
Skip to first unread message

Makoto Yamashita

unread,
Jun 5, 2014, 8:43:46 PM6/5/14
to sage-s...@googlegroups.com
Hi,

I noticed that fractions in nested list comprehensions are apparently interpreted in the Python way. So, with the input
[[j/k for j in range(1,k+1)] for k in range(1,5)]
I get
[[1], [0, 1], [0, 0, 1], [0, 0, 0, 1]] .
With a single level there's no such issue: [j/3 for j in range(1,4)] returns [1/3, 2/3, 1] .
For now I'm dealing with it by enclosing the variables in Integer(). Is there any better solution?

thanks,
Makoto

William Stein

unread,
Jun 5, 2014, 9:13:00 PM6/5/14
to sage-support
This is pretty much *the* worst gotcha of Sage.   You could do this instead:

[[j/k for j in srange(1,k+1)] for k in srange(1,5)]

It makes a range-like object, but respects the types of the input variables of the srange, which are Integer in this case. 

 -- William

 

thanks,
Makoto

--
You received this message because you are subscribed to the Google Groups "sage-support" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sage-support...@googlegroups.com.
To post to this group, send email to sage-s...@googlegroups.com.
Visit this group at http://groups.google.com/group/sage-support.
For more options, visit https://groups.google.com/d/optout.



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

Makoto Yamashita

unread,
Jun 5, 2014, 9:20:23 PM6/5/14
to sage-s...@googlegroups.com
I see, it did work indeed. Thanks!
Makoto

kcrisman

unread,
Jun 5, 2014, 9:46:18 PM6/5/14
to sage-s...@googlegroups.com


This is pretty much *the* worst gotcha of Sage.   You could do this instead:

[[j/k for j in srange(1,k+1)] for k in srange(1,5)]

It makes a range-like object, but respects the types of the input variables of the srange, which are Integer in this case. 


Yup, this is always nasty.  Now, with Python 3 this *sort* of goes away, but am I correct that j/k will then give (floating point) 0.5, not a Rational Sage type, right?  So in some sense this will still be an issue, just a different one. 
Reply all
Reply to author
Forward
0 new messages