algorizm to merge nodes

Gerard flanagan grflanagan at gmail.com
Fri Oct 17 20:50:00 EDT 2008


JD 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?
> 


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


def merge(inlist):
     n = len(inlist)
     outlist = [set(inlist.pop())]
     while inlist:
         s = set(inlist.pop())
         merged = False
         for i in range(len(outlist)):
             t = outlist[i]
             u = s | t
             if len(u) < len(s) + len(t):
                 outlist[i] = u
                 merged = True
                 break
         if not merged:
             outlist.append(s)
     if len(outlist) == n:
         return outlist
     else:
         return merge(outlist)

for s in merge(data):
     print s





More information about the Python-list mailing list