Software Engineering

write a Lazy Repeater Helper in Python

write a Lazy Repeater Helper in Python
Written by admin


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 at first 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

Possibility 1:

from itertools import cycle

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

Possibility 2:

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

Possibility 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 answer

take a look at.describe("Pattern Checks")

abc = make_looper("abc")

take a look at.assert_equals(abc(), 'a')
take a look at.assert_equals(abc(), 'b')
take a look at.assert_equals(abc(), 'c')

take a look at.assert_equals(abc(), 'a')
take a look at.assert_equals(abc(), 'b')
take a look at.assert_equals(abc(), 'c')

About the author

admin

Leave a Comment