Careercup - Google面试题 - 5898529851572224

时间:2022-11-16 06:24:30

2014-05-06 07:56

题目链接

原题:

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

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

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

代码:

 # http://www.careercup.com/question?id=5898529851572224
#!/usr/bin/python def flatten(container, new_container):
for element in container:
if isinstance(element, list) or isinstance(element, tuple) or isinstance(element, set):
flatten(element, new_container)
else:
new_container.append(element)
pass if __name__ == '__main__':
a = [1, 2.3, [3, [1, 222]], (4, 111, 0), "string", set([1, "hello", 3.33])]
res = []
flatten(a, res)
print(res)
pass