Thursday, September 21, 2023
HomeSoftware EngineeringMethods to write a Lazy Repeater Helper in Python

Methods to 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’ll begin again originally of the string as soon as it reaches the top.

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):
    world i
    i = 0
    def inner_function():
        world i
        if i == len(string):
            i = 0
        output = string[i]
        i += 1
        return output
    return inner_function

Take a look at instances to validate our answer

check.describe("Pattern Assessments")

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments