I've seen a few questions asking about list flattening and I was wondering how to retrieve the length of the flattened list without actually flattening it. My list can be arbitrarily deep.
Case 1:
Input:
[[[1, 2], 3], 4]
Output:
4
Case 2:
Input:
[[[[1, 2], [3, 4]], 5], [6, 7]]
Output:
7
Here's a recursive implementation:
def flattenlen(a):
total = 0
for i in range(len(a)):
if type(a[i]) == list:
total += flattenlen(a[i])
else:
total += 1
return total
print flattenlen([[[[1, 2], [3, 4]], 5], [6, 7]])
Output:
7
Does anyone have a closed form solution? Is there a built-in method or a library to achieve this? Is there a more efficient method that I have missed?