程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Weighted sum of Python list elements

編輯:Python

Python Weighted sum of the number of list elements

Title Description

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 .

Input

Enter a list in one line .

Output

Output a number of weighted elements in one line .

The sample input

[1,2,[3,4,[5,6],7],8]

Sample output

15

Run code

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)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved