일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 컴퓨터의 구조
- 파이썬
- 시바견
- 운영체제
- Regular Expression
- t1
- Substring with Concatenation of All Words
- Python Implementation
- 밴픽
- Generator
- data science
- DWG
- concurrency
- attribute
- Python Code
- kaggle
- Convert Sorted List to Binary Search Tree
- LeetCode
- 715. Range Module
- Python
- shiba
- 30. Substring with Concatenation of All Words
- 43. Multiply Strings
- Protocol
- 109. Convert Sorted List to Binary Search Tree
- Decorator
- 프로그래머스
- iterator
- 315. Count of Smaller Numbers After Self
- Class
Archives
- Today
- Total
Scribbling
LeetCode: 341. Flatten Nested List Iterator 본문
Computer Science/Coding Test
LeetCode: 341. Flatten Nested List Iterator
focalpoint 2022. 1. 13. 14:43Making a new list is an easy solution to implement with recursion.
class NestedIterator:
def __init__(self, nestedList: [NestedInteger]):
self.res = []
self._flattener(nestedList)
self.ptr = 0
def _flattener(self, nestedList):
for nl in nestedList:
if nl.isInteger():
self.res.append(nl.getInteger())
else:
self._flattener(nl.getList())
def next(self) -> int:
ret = self.res[self.ptr]
self.ptr += 1
return ret
def hasNext(self) -> bool:
return self.ptr < len(self.res)
# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())
However, above does not seem to act like an real iterator, as it is not lazy.
We can use 'yield' to make something really works like an iterator as below.
class NestedIterator:
def __init__(self, nestedList: [NestedInteger]):
def _generator(nestedList):
for nl in nestedList:
if nl.isInteger():
yield nl.getInteger()
else:
yield from _generator(nl.getList())
self.gen = _generator(nestedList)
self.nextelem = next(self.gen, None)
def next(self) -> int:
ret = self.nextelem
self.nextelem = next(self.gen, None)
return ret
def hasNext(self) -> bool:
return self.nextelem != None
'Computer Science > Coding Test' 카테고리의 다른 글
LeetCode: 384. Shuffle an Array (0) | 2022.01.15 |
---|---|
LeetCode: 378. Kth Smallest Element in a Sorted Matrix (0) | 2022.01.14 |
LeetCode: 334. Increasing Triplet Subsequence (0) | 2022.01.11 |
LeetCode: 329. Longest Increasing Path in a Matrix (0) | 2022.01.11 |
LeetCode: 350. Intersection of Two Arrays II (0) | 2022.01.10 |