Hi,

I have been researching on ways to partition a set into equal quantity sub-sets. I came across this code zip(*[iter(s)]*n) however, the code does process, but it outputs a < zip object at 'HEX code location' > and not the actual set of subsets. I tried using show, and print, but that didn't work. Is there something I am missing?

edit retag close merge delete

Try list

( 2020-12-15 00:25:33 +0200 )edit
1

More precisely: in Python 2, zip would return a list. Nowadays in Python 3 it returns a zip object, which is an iterable, that can be turned into a list with list, i.e. list(zip(*[iter(s)]*n)) will give the corresponding list.

( 2020-12-15 06:47:51 +0200 )edit

( 2020-12-16 03:46:18 +0200 )edit

I expanded the comments into an answer with an example and an alternative solution.

This way the question can appear as answered in the list of questions.

( 2020-12-16 06:56:32 +0200 )edit

Sort by ยป oldest newest most voted

Sage <= 8.9 was based on Python 2 in which zip would return lists.

Sage >= 9.0 is based on Python 3 in which zip returns "zip objects".

Zip objects are iterable, so list can turn them into lists.

Example (from another Ask Sage question):

sage: a = [250, 770, 360, 190, 230, -1, 0, 0, 0, 0, 0, 1, 31,
....:      44, 14, 27, 3, 0, 480, 1770, 800, 580, 160, 0, 1,
....:      0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
....:      0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1]
sage: b = list(zip(*[iter(a)]*6))
sage: b
[(250, 770, 360, 190, 230, -1),
(0, 0, 0, 0, 0, 1),
(31, 44, 14, 27, 3, 0),
(480, 1770, 800, 580, 160, 0),
(1, 0, 0, 0, 0, 0),
(0, 1, 0, 0, 0, 0),
(0, 0, 1, 0, 0, 0),
(0, 0, 0, 1, 0, 0),
(0, 0, 0, 0, 1, 0),
(0, 0, 0, 0, 0, 1)]


Here we could also use matrix:

sage: m = matrix(10, 6, a)
sage: m
[ 250  770  360  190  230   -1]
[   0    0    0    0    0    1]
[  31   44   14   27    3    0]
[ 480 1770  800  580  160    0]
[   1    0    0    0    0    0]
[   0    1    0    0    0    0]
[   0    0    1    0    0    0]
[   0    0    0    1    0    0]
[   0    0    0    0    1    0]
[   0    0    0    0    0    1]


Then we can get a list of rows:

sage: m.rows()
[(250, 770, 360, 190, 230, -1),
(0, 0, 0, 0, 0, 1),
(31, 44, 14, 27, 3, 0),
(480, 1770, 800, 580, 160, 0),
(1, 0, 0, 0, 0, 0),
(0, 1, 0, 0, 0, 0),
(0, 0, 1, 0, 0, 0),
(0, 0, 0, 1, 0, 0),
(0, 0, 0, 0, 1, 0),
(0, 0, 0, 0, 0, 1)]


The rows are really vectors (which display exactly as tuples).

To get actual tuples:

sage: [tuple(row) for row in m]
[(250, 770, 360, 190, 230, -1),
(0, 0, 0, 0, 0, 1),
(31, 44, 14, 27, 3, 0),
(480, 1770, 800, 580, 160, 0),
(1, 0, 0, 0, 0, 0),
(0, 1, 0, 0, 0, 0),
(0, 0, 1, 0, 0, 0),
(0, 0, 0, 1, 0, 0),
(0, 0, 0, 0, 1, 0),
(0, 0, 0, 0, 0, 1)]

more