[Codewars] 094: Lazy Repeater

题目

The makeLooper() function (make_looper in Python) 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.

For example:

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

我的答案

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

其他精彩答案

from itertools import cycle

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

class make_looper(cycle):
    
    def __call__(self):
        return self.__next__()
def make_looper(string):
    def generator():
        while True:
            for char in string:
                yield char
    return generator().next
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容