algorizm to merge nodes

Mensanator mensanator at aol.com
Fri Oct 17 17:00:44 EDT 2008


On Oct 17, 3:20 pm, JD <Jiandong... at gmail.com> wrote:
> Hi,
>
> I need help for a task looks very simple:
>
> I got a python list like:
>
> [['a', 'b'], ['c', 'd'], ['e', 'f'], ['a', 'g'], ['e', 'k'], ['c',
> 'u'], ['b', 'p']]
>
> Each item in the list need to be merged.
>
> For example, 'a', 'b' will be merged, 'c', 'd' will be merged.
>
> Also if the node in the list share the same name, all these nodes need
> be merged.
>
> For example, ['a', 'b'], ['a', 'g'] ['b', 'p'] will be merged to ['a',
> 'b', 'g', 'p']
>
> The answer should be:
>
> [['a', 'b', 'g', 'p'], ['c', 'd', 'u'], ['e', 'f', 'k']]
>
> Anyone has a solution?

A = [['a', 'b'], \
     ['c', 'd'], \
     ['e', 'f'], \
     ['a', 'g'], \
     ['e', 'k'], \
     ['c', 'u'], \
     ['b', 'p']]

merged = []

for i in A:
    if len(merged)==0:
        merged.append(set(i))
    else:
        gotit = False
        for k,j in enumerate(merged):
            u = j.intersection(set(i))
            if len(u):
                merged[k] = j.union(set(i))
                gotit = True
        if not gotit:
            merged.append(set(i))

print merged

##
##    [set(['a', 'p', 'b', 'g']), set(['c', 'u', 'd']), set(['k', 'e',
'f'])]
##




>
> Thanks,
>
> JD




More information about the Python-list mailing list