Enter a nested list , The nesting level is unlimited , Calculate the weighted sum of list elements according to the number of levels .
In the first layer, each element counts as an element , Each element in the second layer is 2 Elements , Each element in the third layer is 3 Elements , Each element in the fourth layer is 4 Elements ,…, And so on .
Enter a list in one line .
Output a number of weighted elements in one line .
[1,2,[3,4,[5,6],7],8]
15
import ast
lists = ast.literal_eval(input()) # Input nested list
global totalnum
totalnum=0
def calnum(lists,w):
global totalnum
neww=w+1
for i in range(0,len(lists)):
if(str(lists[i]).isdigit()):
totalnum=totalnum+w
else:
calnum(lists[i],neww) # The main idea is to use recursion
calnum(lists,1)
print(totalnum)