0

For the following nicely working Python code

#--------------------------------------------------
s = [[1,2,3],[3,6],[9,0],[0,8]]
s = [set(i) for i in s if i]
t = []
while len(t) != len(s):
    t = s
    s = []
    for i in range(len(t)):
        for j in range(len(s)):
            if not s[j].isdisjoint(t[i]):
                s[j] = s[j].union(t[i])
                break
        else: s.append(t[i])
print(s)
#--------------------------------------------------
>>> [{1, 2, 3, 6}, {0, 9, 8}]
#--------------------------------------------------

My translation to Matlab as:

%--------------------------------------------------
s = {[1,2,3],[3,6],[9,0],[0,8]};
t = {};
while length(t) ~= length(s)
    t = s;
    s = {};
    for i=1:length(t)
        for j=1:length(s)
            if ~isempty(intersect(s{j},t{i}))
                s{j} = union(s{j},t{i});
                break
            else
                s = [s; t{i}];
            end
        end
        if isempty(s); s = [s; t{i}]; end
    end
end
s{:}
%--------------------------------------------------
ans =
     1     2     3     6
ans =
     0     8     9
ans =
     0     8
%--------------------------------------------------

works incorrectly!

The Q: What causes this?

Refs: Python: simple list merging based on intersections
Python code after agf

Community
  • 1
  • 1
Developer
  • 8,258
  • 8
  • 49
  • 58

1 Answers1

1

Well, I could find a solution as follows.

%--------------------------------------------------
s = {[1,2,3],[3,6],[9,0],[0,8]};
t = {};
while length(t) ~= length(s)
    t = s;
    s = {};
    for i=1:length(t)
        for j=1:length(s)
            if ~isempty(intersect(s{j},t{i}))
                s{j} = union(s{j},t{i});
                j = 0;
                break;
            end
        end
        if isempty(s) || (j == length(s));
            s = [s; t{i}];
        end
    end
end
s{:}
%--------------------------------------------------
ans =
     1     2     3     6
ans =
     0     8     9

where j = 0; and if isempty(s) || (j == length(s)); satisfy else: as in the Python version.

Developer
  • 8,258
  • 8
  • 49
  • 58