Faced an interview question in Python that was as follow?
ex:
input = (\'192.168.15.1\', \'.\', -1) ===> output = (192, 168, 15, 1)
input = (\'192.168.15
You could solve this task with following function
def split_string(istr,ich,inte):
res = []
prev = 0
for i,ch in enumerate(istr):
if ch == ich:
res.append(istr[prev:i])
prev = i+1
inte = inte-1
if inte == 0:
break
if prev < len(istr):
res.append(istr[prev:])
return res
or another solution
def split_string(istr,ich,inte):
res = []
h,_,r = istr.partition(ich)
while r:
res.append(h)
inte = inte-1
if inte == 0:
h = r
break
h,_,r = r.partition(ich)
if h:
res.append(h)
return res
For following code
print split_string('192.168.15.1', '.', -1)
print split_string('192.168.15.1', '.', 2)
output will be
['192', '168', '15', '1']
['192', '168', '15.1']
Something like this would work:
def splitter(string_, splitchar, maxsplits):
# if maxsplits is positive, split string into maxsplits of parts, on splitchar.
# Otherwise perform as many splits as the string allows.
out = []
sub = []
for ch in string_:
if ch != splitchar:
sub.append(ch)
else:
if maxsplits < 1 or (maxsplits > 0 and (len(out) < maxsplits)):
out.append(''.join(sub))
sub = []
else:
sub.append(ch)
out.append(''.join(sub))
return tuple(out)
>>> splitter.splitter('192.168.15.1', '.', -1)
('192', '168', '15', '1')
>>> splitter.splitter('192.168.15.1', '.', 2)
('192', '168', '15.1')
>>> splitter.splitter('192.168.15.1', '.', 0)
('192', '168', '15', '1')
>>> splitter.splitter('192.168.15.1', '.', 1)
('192', '168.15.1')
Simple and recursive.
def split_str(s,c,i):
if i == 0:
return [s]
else:
head, _, rest = s.partition(c)
if rest:
return [head] + split_str(rest, c, i - 1)
return [head]
def split(text, sep, maxsplit=-1):
parts = []
end = -1
while True:
start = end + 1
end = text.find(sep, start)
if (end == -1) or (maxsplit == 0):
parts.append(text[start:])
break
else:
parts.append(text[start:end])
if maxsplit != 0: maxsplit -= 1
return parts
print(split('192.168.15.1', '.', -1)) # ['192', '168', '15', '1']
print(split('192.168.15.1', '.', 2)) # ['192', '168', '15.1']
another simpler and short approach is you can use regular expressions like this:
import re
def split_without_using_split_fn(s, c, i):
if i<=0:
print(re.findall("[^"+c+"]+(?=\\"+c+"|$)", s))
else:
l=re.findall("[^"+c+"]+(?=\\"+c+"|$)", s)
print(l[0:-i]+[c.join(l[i:])])
split_without_using_split_fn(*('192.168.15.1', '.', -1))
split_without_using_split_fn(*('192.168.15.1', '.', 2))
Output:
$ python3 p.py
['192', '168', '15', '1']
['192', '168', '15.1']
$