Ask Your Question

Revision history [back]

The input

Set([x^2 for x in QQ])

makes Sage first try to evaluate [x^2 for x in QQ], but that is an infinite list, so Sage will never complete that step, it will just fill up memory.

Instead you could define

B = (x^2 for x in QQ)

which is an iterator which can output one by one the squares of rational numbers, but never tries to compute them all at once.

If the reason you were using Set was to avoid duplicates, in this example you can just require x nonnegative:

B = (x^2 for x in QQ if x >= 0)

so that you get each square of a rational only once.

You can then get the first few terms by

sage: [B.next() for _ in xrange(10)]
[0, 1, 1/4, 4, 1/9, 9, 4/9, 9/4, 1/16, 16]

See the thematic tutorial on comprehensions, iterators and iterables for more on that theme.