Sunday, April 14, 2024
HomeSoftware EngineeringFind out how to Create Your Personal Python Cut up Perform

Find out how to Create Your Personal Python Cut up Perform


The problem

Write your individual implementation of the built-in cut up perform in Python.

The next guidelines have to be adhered to:

  • the perform can’t use, in any manner, the unique cut up or rsplit capabilities,
  • the brand new perform should be a generator,
  • it ought to behave because the built-in cut up, so will probably be examined that manner — consider cut up() and cut up('')

The answer in Python

Choice 1:

import re
def my_very_own_split(string, delimiter = None):
    if delimiter == '': elevate ValueError('empty delimiter')
    if delimiter == None: delimiter = 's+'
    else: delimiter = re.escape(delimiter)
    pos = 0
    for m in re.finditer(delimiter, string):
        yield string[pos:m.start()]
        pos = m.finish()
    yield string[pos:]

Choice 2:

import re

def my_very_own_split(s, dell = None):
    f = []
    if dell=='': elevate SyntaxError
    if dell:
        whereas dell in s:
            f.append(s[:s.find(dell)])
            s = s[s.find(dell)+len(dell):]
        return f+[s]
    return re.cut up(r'[s]*',s)

Choice 3:

from string import whitespace, maketrans
convert_whitespace = lambda s: s.translate(maketrans(whitespace, ' ' * len(whitespace)))

def my_very_own_split(strng, sep=None):
    begin, fil = 0, False
    if sep == '': elevate ValueError("empty separator")
    if sep is None: sep, fil, strng = ' ', True, convert_whitespace(strng)
    whereas begin <= len(strng):
        finish = strng.discover(sep, begin)
        if finish < 0: finish = len(strng)
        if not fil or strng[start: end]: yield strng[start: end]
        begin = finish + len(sep)

Check instances to validate our resolution

s, d = 'abc,def,ghi', ','
check.assert_equals(listing(my_very_own_split(s, d)), ['abc', 'def', 'ghi'])

s, d = 'It is a check', ' '
check.assert_equals(listing(my_very_own_split(s, d)), ['This', 'is', 'a', 'test'])

s, d = 'It is a check', ','
check.assert_equals(listing(my_very_own_split(s, d)), ['This is a test'])
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments