list of strings - remove commonalities of common strings
<p>I'm struggling to come up with a way to solve this problem (and how to come up with a name for this question on stackoverflow).</p>

<p>I need to somehow remove commonalities of strings preserving the remainder.  </p>

<p>Given a list such as the following:</p>

<pre><code>l = ('first',
     'first.second',
     'first.second.third',
     'a.b.c',
     'x.y.z',
     'x.y') 
</code></pre>

<p>I'm hoping to have a list output as:</p>

<pre><code>('first',
 'second',
 'third', 
 'a.b.c',
 'x.y',
 'z' ) 
</code></pre>

<p>as you can see, when <code>first.second</code> subtracts <code>first</code> and remains <code>second</code>. <code>first.second</code> is subtracted from <code>first.second.third</code> we get <code>third</code>.  <code>a.b.c</code> doesn't have anything to subtract from itself, so it remains.  <code>x.y</code> is subtracted from <code>x.y.z</code> and <code>z</code> remains.</p>

<p>I'm thinking maybe a <code>sort(key=len)</code> will be part of the solution, as well as some sort of recursion to end up with the string remainder.  I'm hoping for a clean way to remove commonalities of each string in the list. </p>

<p>I think maybe i was trying too get too fancy with list and dict comprehensions. </p>

<p>I believe i was able to solve the problem with the following:</p>

<ol>
<li>sort in-bound list</li>
<li>use a variable for "previous list element" </li>
<li>loop, and output the the current element replacing previous element (if it is found)  </li>
</ol>

<p>Here's what i have so far:</p>

<pre><code>li = [
     'first',
     'first.second',
     'first.second.third',
     'a',
     'a.b',
     'a.b.c',
     'x.y.z',
     'x.y'] 

li.sort() 

prev_l = ''
output = {} 
for l in li:
    if l.find(prev_l) ==0:
        output[l] = l.replace(prev_l,'')
    else: 
        output[l] = l
    prev_l = l
</code></pre>

<p>output:</p>

<pre><code>{
'a'                   : 'a',
'a.b'                : '.b',
'a.b.c'              : '.c',
'first'              : 'first',
'first.second'       : '.second',
'first.second.third' : '.third',
'x.y'                : 'x.y',
'x.y.z'              : '.z'}
</code></pre>

python algorithm