[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
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 13,182评论 0 13
  • Pathname lookup in Linux. This write-up is based on three...
    朔飞阅读 4,086评论 0 0
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 7,956评论 0 0
  • 2018年5月18日对于我来说是一个成长中有惊喜的日子,我作为骨干教师代表同鞍山市铁西区各校的教学校长一起...
    鞍山晓军阅读 4,671评论 0 6
  • 二零一九年的最后一天了,明天就是元旦了,开启新的一年了。在这旧年里,我独自立于窗前。 看着窗里窗外,冷风时不时的骚...
    行百里者半九十阅读 1,337评论 0 1

友情链接更多精彩内容