-->
当前位置:首页 > 题库

PROGRAMMING:Weighted sum of the number of list elements (1)

Luz5年前 (2021-05-10)题库525
Enter a nested list with unlimited nesting levels, and calculate the weighted sum of list elements according to the levels. Each element in the first layer counts as one element, each element in the second layer counts as two elements, each element in the third layer counts as three elements, each element in the fourth layer counts as four elements, and so on!
###Input format:
Enter a list on one line.
###Output format:
Output a number of weighted elements in a row.
###Input example:
Here is a set of inputs. For example:
```in
[1,2,[3,4,[5,6],7],8]
```
###Output example:
The corresponding output is given here. For example:
```out
fifteen
```







answer:If there is no answer, please comment
```
from collections import Iterable
def flatten(items,level):
for x in items:
if isinstance(x,Iterable):
yield from flatten(x,level+1)
else:
yield x*level
items=eval(input())
l=[x for x in flatten(items,1)]
print(sum([x for x in flatten(items,1)]))
```