1

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
1
  • I think you're going to need to walk me through the negative integer case... Commented Mar 17, 2016 at 6:39

5 Answers 5

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]
Sign up to request clarification or add additional context in comments.

Comments

0
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']

Comments

0

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')

Comments

0

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']
$

1 Comment

You could unpack the input argument to make the code muuuuuch more easier to read. Just s, c, i = input as the first line of the function. Or you could just put them as the function's arguments just like in OPs own code.
0

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.