# Playing with finite sets

Hello, I would like to know if anyone can give me some hint to do the following to the next level without repeating all routines below for m=5, where m is the number of elements fo M:

p = dict()
M = FiniteEnumeratedSet([1 .. 4])
P = cartesian_product([M]*4)
for i in (1 .. 4):
for u in (1 .. 4):
p[i, u] = [1 if P[m][i-1] == u else 0 for m in (0 .. 255)]
P1 = matrix([p[i,j] for i in (1..4) for j in (1..4)])


and

for i in (1 .. 4):
for u in (1 .. 4):
for j in (1..4):
for v in (1..4):
if i <= j:
p[i,j, u,v] = [1 if P[m][i-1] == u and P[m][j-1] == v else 0 for m in (0 .. 255)]
P2 = matrix([p[i,j,u,v] for i in (1..4) for j in (1..4) for u in (1..4) for v in (1..4)
if i <= j])


and

for i in (1 .. 4):
for u in (1 .. 4):
for j in (1..4):
for k in (1..4):
for v in (1..4):
for w in (1..4):
if i <= j and j <= k:
p[i,j,k, u,v,w] = [1 if P[m][i-1] == u and
P[m][j-1] == v and
P[m][k-1] == w else 0 for m in (0 .. 255)]
P3 = matrix([p[i,j,k, u,v,w] for i in (1..4) for j in (1..4) for u in (1..4) for v in (1..4) for k in (1..4) for w in (1..4) if i <= j and j <= k])


and finally

P1.rank()
P2.rank()
P3.rank()

edit retag close merge delete

Sort by » oldest newest most voted

There is a nice module named itertools for sich things, here is how you can use product it provides in you context:

As an example, you can replace nested loops:

sage: for i0 in range(1,5):
....:     for i1 in range(1,5):
....:         for i2 in range(1,5):
....:             print('{} sdf {} fds {}'.format(i0, i1, i2))
....:             print('the sum is {}'.format(i0 + i1 + i2))


with a single loop over the product:

sage: import itertools
sage: for i in itertools.product(range(1,5), repeat=3):
....:     print('{} sdf {} fds {}'.format(*i))
....:     print('the sum is {}'.format(i[0] + i[1] + i[2]))

more

( 2021-07-30 23:44:16 +0200 )edit