How to generate k+1 length strings from a list of k length strings?

Boris Borcic bborcic at gmail.com
Thu Jun 8 10:42:48 EDT 2006


Girish Sahani wrote:
>  I have a list of strings all of length k. For every pair of k length
> strings which have k-1 characters in common, i want to generate a k+1
> length string(the k-1 common characters + 2 not common characters).
> e.g i want to join 'abcd' with bcde' to get 'abcde' but i dont want to
> join 'abcd' with 'cdef'
>  Currently i'm joining every 2 strings, then removing duplicate characters
> from every joined string and finally removing all those strings whose
> length != k+1.

Hum, since your code is not syntactically correct, anything will run faster :)
I'd favor the following, that I find most readable

sets = map(set,list_of_strings)
res = set(''.join(sorted(s1|s2)) for s1 in sets for s2 in sets if len(s1^s2)==2)

unless performance is really an issue

Here's the code i've written:
> 
>       for i in range(0,len(prunedK) - 1,1):
>         if k in range(1,len(prunedK),1) & i+k <= len(prunedK) -1:
>             colocn = prunedK[i] + prunedK[i+k]
>             prunedNew1.append(colocn)
>             continue
>         for string in prunedNew1:
>             stringNew = withoutDup(string)
>             prunedNew.append(stringNew)
>             continue
> 
> But this one is quite bad in the time aspect :(

how do you know ?

> Thanks in advance,
> girish

you should do your own homework



More information about the Python-list mailing list