Fwd: Re: Wrapping around a list

Ricardo Aráoz ricaraoz at gmail.com
Thu Nov 28 13:38:23 EST 2013


El 27/11/13 07:46, amjadcsu at gmail.com escribió:
> Hello,
> I am working on a problem (Bioinformatics domain) where all possible combinations of input string needs to be printed as sublist
>
> For example:
> Input string : "LEQN"
> Output= "[L","E","Q","N"]["LE","EQ","QN","NL"] ["LEQ","EQN","QNE","NLE"]
> ["LEQN"]
>
> The code i have written for this is as follows:
>
> from itertools import chain, repeat, islice
> from collections import deque
>
> def sliding_window(iterable, n, fill=False, fillvalue=None):
>      it = iter(iterable)
>      if fill:
>          it = chain(it, repeat(fillvalue, n - 1))
>      w = deque(islice(it, n - 1))
>      for x in it:
>          w.append(x)
>          yield w
>          w.popleft()
>
> input="LENQ"
>
> lstinput= list(input)
> lenlstinput=len(lstinput)
> list1=[''.join(x) for x in sliding_window(lstinput, 2)]
> list2= [''.join(x) for x  in sliding_window(lstinput, 3)]
> list3= [''.join(x) for x in sliding_window(lstinput, 4)]
>
>
>
> The output i get as follows:
> List 1 is  ['LE', 'EN', 'NQ']   Should be ['LE','EN','NQ','QL']
>   List 2 is  ['LEN', 'ENQ']      Should be ['LEN','ENQ','NQL','QLE']
>
> So the question i am asking , how can i add wrapping around sublist in my sliding window function.
>
> Thanks

Easy :

def getSlice(iterable, start, n):
     lit = len(iterable)
     end = start + n
     return ''.join(iterable[i%lit] for i in range(start, end))


for n in range(1, len(inStr)+1):
     [getSlice(inStr, i, n) for i in range(len(inStr))]


results :

['L', 'E', 'Q', 'N']
['LE', 'EQ', 'QN', 'NL']
['LEQ', 'EQN', 'QNL', 'NLE']
['LEQN', 'EQNL', 'QNLE', 'NLEQ']







More information about the Python-list mailing list