Created
April 13, 2016 03:33
-
-
Save suzaku/46748559ac0df37f3bc6b5998e0585f5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from collections import deque | |
| def flatten(list_): | |
| return list(iflatten(list_)) | |
| def iflatten(list_): | |
| seen = set() | |
| list_ = deque(list_) | |
| while list_: | |
| item = list_.popleft() | |
| if isinstance(item, list): | |
| if id(item) in seen: | |
| raise TypeError | |
| else: | |
| seen.add(id(item)) | |
| while item: | |
| list_.appendleft(item.pop()) | |
| else: | |
| yield item | |
| if __name__ == '__main__': | |
| print(flatten([[1, 2, [3]], [4, [5]]])) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def flatten(list_): | |
| return list(iflatten(list_)) | |
| def iflatten(list_, seen=None): | |
| if seen is None: | |
| seen = set() | |
| if id(list_) in seen: | |
| raise TypeError | |
| else: | |
| seen.add(id(list_)) | |
| for i in list_: | |
| if isinstance(i, list): | |
| yield from iflatten(i, seen) | |
| else: | |
| yield i | |
| if __name__ == '__main__': | |
| print(flatten([[1, 2, [3]], [4, [5]]])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment