HomeSoftware Engineeringwrite a Lazy Repeater Helper in Python

write a Lazy Repeater Helper in Python


The problem

The make_looper() operate takes a string (of non-zero size) as an argument. It returns a operate. The operate it returns will return successive characters of the string on successive invocations. It’s going to begin again at the start of the string as soon as it reaches the tip.

Examples:

abc = make_looper('abc')
abc() # ought to return 'a' on this primary name
abc() # ought to return 'b' on this second name
abc() # ought to return 'c' on this third name
abc() # ought to return 'a' once more on this fourth name

The answer in Python code

Choice 1:

from itertools import cycle

def make_looper(s):
    g = cycle(s)
    return lambda: subsequent(g)

Choice 2:

def make_looper(string):
    def generator():
        whereas True:
            for char in string:
                yield char
    return generator().subsequent

Choice 3:

def make_looper(string):
    international i
    i = 0
    def inner_function():
        international i
        if i == len(string):
            i = 0
        output = string[i]
        i += 1
        return output
    return inner_function

Check instances to validate our resolution

check.describe("Pattern Checks")

abc = make_looper("abc")

check.assert_equals(abc(), 'a')
check.assert_equals(abc(), 'b')
check.assert_equals(abc(), 'c')

check.assert_equals(abc(), 'a')
check.assert_equals(abc(), 'b')
check.assert_equals(abc(), 'c')
RELATED ARTICLES

Most Popular

Recent Comments