algorizm to merge nodes

Mensanator mensanator at aol.com
Fri Oct 17 20:42:08 EDT 2008


On Oct 17, 4:34 pm, JD <Jiandong... at gmail.com> wrote:
> Hi,
>
> Thanks,
>
> It works for this example,
>
> but if I add another item ['e', 'd']:
> [['a', 'b'], \
>      ['c', 'd'], \
>      ['e', 'f'], \
>      ['a', 'g'], \
>      ['e', 'k'], \
>      ['c', 'u'], \
>      ['b', 'p'],\
>      ['e', 'd']]
>
> The result is
> set(['a', 'p', 'b', 'g']), set(['e', 'c', 'u', 'd']), set(['k', 'e',
> 'd', 'f'])
>
> The right result should be:
>
> ['a', 'p', 'b', 'g'], ['c', 'u', 'e', 'd', 'k', 'f']
>
> JD
>
> On Oct 17, 3:00 pm, Mensanator <mensana... at aol.com> wrote:
>
>
>
> > 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']]

Well, you should have asked for that, if that's what you wanted.

>
> > > Anyone has a solution?
>
> > A = [['a', 'b'], \
> >      ['c', 'd'], \
> >      ['e', 'f'], \
> >      ['a', 'g'], \
> >      ['e', 'k'], \
> >      ['c', 'u'], \
> >      ['b', 'p']]
>

A.sort()

> > 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'])]
> > ##


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


>
> > > Thanks,
>
> > > JD





More information about the Python-list mailing list