题目
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