Как разделить строку в зависимости от длины в seqeunce в python? - PullRequest
0 голосов
/ 26 марта 2020
>>>'mymedicinesarerighthere'

Вам нужно разбить это слово следующим образом:

>>>['m', 'ym', 'edi', 'cine', 'sarer', 'ighthe', 're']

Ответы [ 5 ]

4 голосов
/ 26 марта 2020

Вот python версия генератора.

def gen(a):
    start=0
    step=1
    while a[start:start+step]:
        yield a[start:start+step]
        start+=step
        step+=1

list(gen('mymedicinesarerighthere'))
# ['m', 'ym', 'edi', 'cine', 'sarer', 'ighthe', 're']

Вот другой подход.

Вы можете заметить, что стартовые индексы каждого среза равны 0,1, 3,6,10 ... их разница между n th и n-1th в AP 1,2,3, 4,5 ... .

Чтобы получить число разделов, вы должны решить это уравнение.

<b>=>(n*(n+1))/2=len(string)</b>
<b>=>n^2+n-2*len(string)=0</b>

Примите значение ceil для n, используя math.ceil(n) даст нам количество разделов здесь это 7, когда длина строки равна 23.

import math
def start(n):
    return n*(n+1)//2
def findRoots(c):
    a=b=1
    d = b * b - 4 * a * c 
    sqrt_val = math.sqrt(abs(d))
    return math.ceil((-b + sqrt_val)/(2 * a))
out=[s[start(i-1):start(i-1)+i] for i in range(1,findRoots(-2*len(s))+1)]
# ['m', 'ym', 'edi', 'cine', 'sarer', 'ighthe', 're']
2 голосов
/ 26 марта 2020

Это довольно чистое решение с использованием некоторых itertools:

from itertools import count, islice

def chunks(s):
    i = iter(s)
    for n in count(1):
        chunk = ''.join(islice(i, n))
        if not chunk:
            return
        yield chunk

>>> list(chunks("mymedicinesarerighthere"))
['m', 'ym', 'edi', 'cine', 'sarer', 'ighthe', 're']
1 голос
/ 26 марта 2020
s='mymedicinesarerighthere'
res=[]
i,x=0,1
while (i+x)<len(s):
    res.append(s[i:x+i])
    i=i+x
    x=x+1
res.append(s[i:len(s)])
print(res)

выход:

['m', 'ym', 'edi', 'cine', 'sarer', 'ighthe', 're']
1 голос
/ 26 марта 2020

Код

txt = "mymedicinesarerighthere"

i = 0
k = 1
myList = []
while i+k < len(txt):
  myList.append(txt[i:i+k])
  i += k
  k += 1
myList.append(txt[i: len(txt)])
print(myList)

Выход

['m', 'ym', 'edi', 'cine', 'sarer', 'ighthe', 're']
0 голосов
/ 26 марта 2020

Ниже приведено решение:

tmpStr = "mymedicinesarerighthere"

splitList = []

ind = 1
while True:
    if len(tmpStr) > ind:
        splitList.append(tmpStr[0:ind])
        tmpStr = tmpStr[ind:]
        ind += 1
    else:
        splitList.append(tmpStr)
        break

print(splitList)

>>> ['m', 'ym', 'edi', 'cine', 'sarer', 'ighthe', 're']
...