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.1', '.', 2) ===> output = ( 192, 168, 15.1 )
Solve such that input(string,char,integer) will give the output such that the string is splited by the character and if integer is 0 or less than that else string is splited the number of by character where character split only occur for the value of integer.
I have written the code although it works fine within boundary and no error condition. Is there a better code out there plese share.
Thanks
def split_string(string,ch,inte):
q = string
c = ch
i = inte
s =list(q)
#Check if integer value is negative or positive
if i <= 0:
# split the string one time
r1 = split_once(s,c)
print r1
else:
#split according to the integear value
r2 = split_acc_intger(s,c,i)
print r2
def split_once(s,c):
y = 0
d = []
for x in range(len(s)):
if s[x] == c:
p=s[y:x]
d.append(''.join(p))
y = x + 1
elif x == len(s)-1:
p=s[y:]
d.append(''.join(p))
return d
def split_acc_intger(s,c,i):
y = 0
d =[]
count = 1
for x in range(len(s)):
# the leat number will 1
if s[x] == c:
p=s[y:x]
d.append(''.join(p))
y = x + 1
count += 1
elif count == i :
p=s[y:]
d.append(''.join(p))
break
return d