Ask Your Question
1

return lists that do not share all of the same elements

asked 2019-04-14 18:19:37 +0100

merluza gravatar image

I am having Sage generate an array of lists for me, but I do not want it to give me the lists that have all of the same elements. For example, if Sage gives me

[1 2 3 4]

[2 3 4 1]

[1 3 4 2]

I only want Sage to give me [1 2 3 4]. I want to create a new array with these non-repeated lists. How do I do that? Thank you!

edit retag flag offensive close merge delete

3 Answers

Sort by » oldest newest most voted
2

answered 2019-04-14 22:16:52 +0100

Emmanuel Charpentier gravatar image

As usual, Éric is right but delphic (pythic ?)... Try this

L=[]
S=set(L)
for u in (your generator):
    s=set(u)
    if s not in S:
        L.extend(u) ## Maybe L.extend(copy(u)) if sharing structures may be a problem later...
        S.add((s)
L

At the end of execution, L should contain lists differing by at least one element.

edit flag offensive delete link more
1

answered 2019-04-15 02:15:27 +0100

Juanjo gravatar image

updated 2019-04-15 02:19:21 +0100

Assume that your array of lists is stored in my_lists. Then, the lines

sets = map(set,my_lists)
union(map(tuple,sets))

do the trick. You get a list of tuples whose elements are unique, as wanted. For example, if

my_lists = Permutations([3,1,2]).list() + Permutations([6,5,4]).list()

then the above two lines yield

[(4, 5, 6), (1, 2, 3)]
edit flag offensive delete link more
0

answered 2019-04-14 18:49:00 +0100

eric_g gravatar image

Use sets, not lists:

sage: set([1, 2, 3, 4])
{1, 2, 3, 4}
sage: set([2, 3, 4, 1])
{1, 2, 3, 4}
sage: set([1, 2, 3, 4]) == set([2, 3, 4, 1])
True
edit flag offensive delete link more

Comments

I am not creating the lists. I am running an iterator and Sage gives me lists. I want it to return lists with distinct elements.

merluza gravatar imagemerluza ( 2019-04-14 20:51:33 +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

2 followers

Stats

Asked: 2019-04-14 18:19:37 +0100

Seen: 489 times

Last updated: Apr 15 '19