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

PROGRAMMING:Weighted sum of list elements (2)

Luz5年前 (2021-05-10)题库524
Enter a nested list, nesting level is not more than 10, according to the level, the weighted number of list elements and. Regardless of the actual level of the input nested list, each element in the first layer counts 10 elements, each element in the second layer counts 9 elements, each element in the third layer counts 8 elements, each element in the fourth layer counts 7 elements,... Each element in the tenth layer counts one element.
For example: [1,2, [3,4, [5,6], 7], 8]
Calculation method: 1 '* ` 10 + 1' * ` 10 + 1 '* ` 9 + 1' * ` 9 + 1 '* ` 8 + 1' * ` 8 + 1 '* ` 9 + 1' * ` 10 = 73
###Input format:
Enter the list on one line
###Output format:
The weighted sum of the number of output 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
seventy-three
```







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
yield level
d={10:1,9:2,8:3,7:4,6:5,5:6,4:7,3:8,2:9,1:10}
items=eval(input())
ln=[x for x in flatten(items,1)]
print(sum(d[i] for i in ln))
```