Ask Your Question

Revision history [back]

If you really want something short, yo can do something along the lines:

sage: from itertools import ifilter, islice
sage: list(islice(ifilter(lambda x: x !=0 , (GF(25).random_element() for _ in ZZ)), 10))

Explanataion:

  • (GF(25).random_element() for _ in ZZ) creates an infinite iterator of random elements of GF(25)
  • ifilter(lambda x: x !=0 , (GF(25).random_element() for _ in ZZ)) creates an iterator that filters the nonzero elements
  • islice(ifilter(lambda x: x !=0 , (GF(25).random_element() for _ in ZZ)), 10) creates an iterator that produces only the first 10 elements of the previous iterator
  • list(islice(ifilter(lambda x: x !=0 , (GF(25).random_element() for _ in ZZ)), 10)) transforms the previous iterator into a list

As for the first line, itertools is a standard module with very nice tools for creating iterators.

That said, if you do:

sage: import this

You will see that Readability counts, so your code is probably the best since you will be able to understand and modify it later.

If you really want something short, yo can do something along the lines:

sage: from itertools import ifilter, islice
sage: list(islice(ifilter(lambda x: x !=0 , (GF(25).random_element() for _ in ZZ)), 10))

Explanataion:

  • (GF(25).random_element() for _ in ZZ) creates an infinite iterator of random elements of GF(25)
  • ifilter(lambda x: x !=0 , (GF(25).random_element() for _ in ZZ)) creates an iterator that filters the nonzero elements
  • islice(ifilter(lambda x: x !=0 , (GF(25).random_element() for _ in ZZ)), 10) creates an iterator that produces only the first 10 elements of the previous iterator
  • list(islice(ifilter(lambda x: x !=0 , (GF(25).random_element() for _ in ZZ)), 10)) transforms the previous iterator into a list

As for the first line, itertools is a standard module with very nice tools for creating iterators.

That said, if you do:

sage: import this

You will see that Readability counts, so your code is probably the best since you will be able to understand and modify it later.

EDIIT, if you want to use it when Sage will use Python3, you just have to replace the imported ifilter with the builtin filter:

sage: from itertools import islice
sage: list(islice(filter(lambda x: x !=0 , (GF(25).random_element() for _ in ZZ)), 10))