Solving split string in python without the use of split() function

后端 未结 5 514
野趣味
野趣味 2021-01-15 20:59

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         


        
5条回答
  •  春和景丽
    2021-01-15 21:20

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

提交回复
热议问题