Created
January 11, 2021 05:28
-
-
Save Himan10/d8e711c0712fe79c95a779262a52cbc0 to your computer and use it in GitHub Desktop.
Implementation of str.split() in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Implementation of split method | |
def split(string: str, separator: str, max_split=-1): | |
if separator.__len__() == 0 or string.__len__() == 0: | |
raise ValueError | |
result = [] | |
temp = '' | |
i = 0 | |
s_index = 0 | |
full_match = False | |
for _, i in enumerate(string): | |
if not full_match: | |
if i == separator[s_index]: | |
s_index += 1 if not full_match else 0 | |
temp += i | |
if s_index == len(separator): | |
full_match = True | |
else: | |
continue | |
if full_match: | |
# Push into stack | |
#print(temp) | |
if max_split: | |
result.append(temp[:-s_index]) | |
max_split -= 1 | |
temp = '' | |
s_index = 0 | |
full_match = False | |
else: | |
# Keep on capturing | |
temp += i | |
s_index = 0 | |
result.append(temp) | |
return result | |
def test(string, delim, max_delim=-1): | |
return split(string, delim, max_delim) == string.split(delim, max_delim) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment