题目
给你一个嵌套的整型列表。请你设计一个迭代器,使其能够遍历这个整型列表中的所有整数。
列表中的每一项或者为一个整数,或者是另一个列表。其中列表的元素也可能是整数或是其他列表。
示例 1:
输入: [[1,1],2,[1,1]]输出: [1,1,2,1,1]解释: 通过重复调用 next 直到 hasNext 返回 false,next 返回的元素的顺序应该是: [1,1,2,1,1]。
示例 2:
输入: [1,[4,[6]]]输出: [1,4,6]解释: 通过重复调用 next 直到 hasNext 返回 false,next 返回的元素的顺序应该是: [1,4,6]。
题解
首先,我们很容易写出直接将列表展开的代码:
def Flatten_List(L):
for i in L:
if type(i) == int:
yield i
else:
yield from Flatten_List(i)
然后,我心想怎么这么简单,就稍微修改一下就交了上去,结果是无情的报错!!!
class NestedIterator:
def __init__(self, nestedList):
self.L = self.List_iter(nestedList)
def List_iter(self, L):
for i in L:
if type(i) == list:
yield from self.List_iter(i)
else:
yield i
def next(self):
return self.val
def hasNext(self) -> bool:
try:
self.val = next(self.L)
return True
except StopIteration:
return False
为啥呢?我在本地运行也没问题啊,很正常啊!
L = [[1, 1], 2, [1, 1]]
i = NestedIterator([[1, 1], 2, [1, 1]])
while i.hasNext():
print(i.next())
# 1
# 1
# 2
# 1
# 1
这提醒我们,一定要认真看代码框中的注释代码:
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger:
# def isInteger(self) -> bool:
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# """
#
# def getInteger(self) -> int:
# """
# @return the single integer that this NestedInteger holds, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# """
#
# def getList(self) -> [NestedInteger]:
# """
# @return the nested list that this NestedInteger holds, if it holds a nested list
# Return None if this NestedInteger holds a single integer
# """
class NestedIterator:
def __init__(self, nestedList: [NestedInteger]):
def next(self) -> int:
def hasNext(self) -> bool:
# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())
这里的输入不是普通的List,而是它自己定义的一个数据结构 NestedInteger。。。
一把辛酸泪,谁知道我修改了半天,结果居然错在这里。。。
class NestedIterator:
def __init__(self, nestedList: [NestedInteger]):
self.L = self.nested_iter(nestedList)
def nested_iter(self, L: [NestedInteger]):
for i in L:
if i.isInteger():
yield i.getInteger()
else:
yield from self.nested_iter(i.getList())
def next(self) -> int:
return self.val
def hasNext(self) -> bool:
try:
self.val = next(self.L)
return True
except StopIteration:
return False

