Ask Your Question

Create an infinite set with list comprehension

asked 2014-07-21 10:12:46 +0100

Vasile gravatar image

Hello. In Sage is possible to create B = Set(Primes()). For B Sage says Set of all prime numbers: 2, 3, 5, 7, ... . So B is infinite. I try to create now a set C = Set([x^2 for x in QQ]). I am expecting to get something similar like above, but Sage does not get so far. After some 20 Minutes of waiting I broke down the action. Is possible to create an infinite Set with list comprehension? I know that lists should befinite but the notation used by list comprehension is very near on the mathematical way to describe a set like D = Set([x^2 for x in range(10)]) for example. Any help appreciated. Thank you and regards, Vasile

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2014-07-21 15:22:39 +0100

slelievre gravatar image

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: [ 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.

edit flag offensive delete link more


Hello, thank you for the answer. The reason for using Set was, that I wanted to operate with Sage sets. I wanted to do some set theory operations like union or difference of two sets. I thought the members of an operation like A = Set(B.difference(C)) should be all the same type. Thank you. Vasile

Vasile gravatar imageVasile ( 2014-07-21 15:30:52 +0100 )edit

Another remark: a 'generator' object has no attribute 'cardinality'. So if I want to work with this, I am getting the error "'generator' object has no attribute 'cardinality'". This was another reason I wanted to work with sets.

Vasile gravatar imageVasile ( 2014-07-21 15:35:27 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2014-07-21 10:12:46 +0100

Seen: 474 times

Last updated: Jul 21 '14