2014-05-06 07:56

题目链接

原题:

Flatten an iterator of iterators in Java. If the input is [ [1,2], [3,[4,5]], 6], it should return [1,2,3,4,5,6]. Implement hasNext() and next(). Note that the inner iterator or list might be empty.

题目:给定一个动态类型的数组,把其中的数组全部展开,成为一个一维数组。

解法:严格类型语言显然不允许这种数据,所以我用Python写了一版代码。

代码:

 1 # http://www.careercup.com/question?id=5898529851572224
 2 #!/usr/bin/python
 3 
 4 def flatten(container, new_container):
 5     for element in container:
 6         if isinstance(element, list) or isinstance(element, tuple) or isinstance(element, set):
 7             flatten(element, new_container)
 8         else:
 9             new_container.append(element)
10     pass
11     
12 if __name__ == '__main__':
13     a = [1, 2.3, [3, [1, 222]], (4, 111, 0), "string", set([1, "hello", 3.33])]
14     res = []
15     flatten(a, res)
16     print(res)
17     pass
18     

 

 posted on 2014-05-06 09:53  zhuli19901106  阅读(209)  评论(0编辑  收藏  举报