假设我们有两件事。
[1, 2, [3, 4, [5],['hi']], [6, [[[7, 'hello']]]]]
def faze_em(it):
"""
`it` is an iterator to characters
For example:
ch = next(it)
# ch == "K"
ch = next(it)
# ch == "I"
ch = next(it)
# ch == "W"
ch = next(it)
# ch == "I"
"""
return "".join(reversed(it))
如何为
some_function
制作装饰器,将深度嵌套的容器转换为单个字符迭代器?
@CharStream.charify
def faze_em(it):
pass
装饰器将返回一个包装函数。
wrapper 函数将深度嵌套的容器转换为 char 流(这样的迭代器
__next__
总是返回长度为 1 的字符串)。
所有函数参数(函数输入)必须是flattened.
也就是说,深层嵌套的字符串容器成为单个字符串字符的扁平浅层容器(或迭代器,如果不是容器的话)。
每个不是字符串的不可迭代的(整数、浮点数等)都应该转换为字符串。
以下所有函数调用都应返回相同的值:
r = faze_em([1, 2, [3, 4, [5],['hi']], [6, [[[7, 'hello']]]]])
r = faze_em(1, 2, 3, 4, 5, 'hi' , 6, 7, 'hello')
r = faze_em(1)( 2)( 3, 4)( 5, 'hi')( 6, 7, 'hello')
r = faze_em(iter(["1", "2", "3", "4", "5", "h", "i", "6", "7", "h", "e", "l", "l", "o"]))
杂乱的容器变成了单一的字符流:
"1", "2", "3", "4", "5", "h", "i", "6", "7", "h", "e", "l", "l", "o"
以下代码代表了实现这一目标的不完整尝试。
我把决定权交给你,是从头开始编写代码还是编辑以下代码。
如果你愿意,你现在可以停止阅读了。
import functools
class CharStream:
def __init__(this, ugly_container):
if hasattr(ugly_container, "__iter__"):
this._it = iter(ugly_container)
else:
this._it = iter(str(ugly_container))
def __iter__(this):
return this
class CharredFunction:
def __init__(this):
pass
def __call__(this, *args, **kwargs):
this.
return this._kallable(*args, **kwargs)
@classmethod
def charify(constructor, kallable):
assert(callable(kallable))
wrapper = constructor(kallable)
wrapper = functools.wraps(wrapper, kallable)
# TO DO:
# figure out whether to use the `assign` or `update`
# parameter for functools.wraps
return chr_strm
def __next__(this):
try:
front = next(this._it)
if isinstance(front, str):
ch = next(iter(front))
this._it = itertools.chain(front, this._it)
elif hasattr(front, "__iter__"):
raise NotImplementedError()
# ch = next(iter(front))
# this._it = itertools.chain(front, this._it)
else: # front is not a string and front is not iterable
this._it = iter(str(front))
this._it = itertools.chain(next(type(this)(front)))
ch = next(this)
return ch
except StopIteration:
# raise type(this).CustomStopIterationException()
raise StopIteration()