How to Write a Lazy Repeater Helper in Python


The challenge

The make_looper() function takes a string (of non-zero length) as an argument. It returns a function. The function it returns will return successive characters of the string on successive invocations. It will start back at the beginning of the string once it reaches the end.

Examples:

abc = make_looper('abc')
abc() # should return 'a' on this first call
abc() # should return 'b' on this second call
abc() # should return 'c' on this third call
abc() # should return 'a' again on this fourth call

The solution in Python code

Option 1:

from itertools import cycle

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

Option 2:

def make_looper(string):
    def generator():
        while True:
            for char in string:
                yield char
    return generator().next

Option 3:

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

Test cases to validate our solution

test.describe("Sample Tests")

abc = make_looper("abc")

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

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