Good afternoon,
Got problem with implementing a function that works like str.split
method,
Cannot resolve specific assert, where upon repeating symbols in separator are not counted properly.
Expected output is [‘set’, ”, ’23’], but upon my code-solution I receive [‘set’, ’23’]
from typing import List
def split(data: str, sep=None, maxsplit=-1):
if data == '':
return []
if sep is None:
sep = ' '
if maxsplit == 0:
return [data.strip()]
parts = []
current_part = ''
split_count = 0
sep_length = len (sep)
counter = 0
while data and data[counter] == ' ':
counter+=1
while counter < len(data):
if data[counter:counter+sep_length] == sep:
if split_count < maxsplit or maxsplit == -1:
parts.append(current_part)
split_count += 1
while data[counter:counter+sep_length] == sep:
if counter < len(data):
counter += sep_length
current_part = ''
else:
current_part += data[counter]
counter += 1
else:
current_part += data[counter]
counter += 1
parts.append(current_part)
print (parts)
return parts
if __name__ == '__main__':
assert split('') == []
assert split(',123,', sep=',') == ['', '123', '']
assert split('test') == ['test']
assert split('Python 2 3', maxsplit=1) == ['Python', '2 3']
assert split(' test 6 7', maxsplit=1) == ['test', '6 7']
assert split(' Hi 8 9', maxsplit=0) == ['Hi 8 9']
assert split(' set 3 4') == ['set', '3', '4']
assert split('set;:23', sep=';:', maxsplit=0) == ['set;:23']
assert split('set;:;:23', sep=';:', maxsplit=2) == ['set', '', '23']
I tried to reformat conditions on counting consecutive separators, but failed to return results properly
New contributor
Stryuk Maxim is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.