在Python中实现运行长度字符串解码迭代器类的程序
假设我们想定义一个迭代器类,它用一个运行长度编码的小写字符串比如s来构造,这个迭代器有两个函数,它们是-
next()this找到迭代器中的下一个元素
hasnext()这会检查下一个元素是否存在
所以,如果输入像s="2b1a",那么用s构造一个对象,然后调用next(),hasnext(),next(),next(),hasnext(),那么输出将是"b",True,"b","a",False。
示例
让我们看看以下实现以获得更好的理解-
class RunLengthIterator: def __init__(self, s): self.output = [] num = "" for i in s: if i.isalpha(): self.output.append(int(num)) self.output.append(i) num = "" else: num += i def next(self): if self.hasnext(): count = self.output[0] letter = self.output[1] count -= 1 if count > 0: self.output[0] -= 1 else: self.output= self.output[2:] return letter def hasnext(self): if len(self.output) != 0: return True return False s = "2b1a" obj = RunLengthIterator(s) print(obj.next()) print(obj.hasnext()) print(obj.next()) print(obj.next()) print(obj.hasnext())
输入
"2b1a" obj = RunLengthIterator(s) obj.next() obj.hasnext() obj.next() obj.next() obj.hasnext()输出结果
b True b a False