輸入一個嵌套列表,再輸入層數,求該層的數字元素個數。
輸入格式:
第一行輸入列表 第二行輸入層數
輸出格式:
在一行中輸出元素個數
輸入樣例:
在這里給出一組輸入。例如:
[1,2,[3,4,[5,6],7],8] 3
輸出樣例:
在這里給出相應的輸出。例如:
2
1 # 求指定層的元素個數
2 # Author: cnRick
3 # Time : 2020-4-13
4 def getSum(items,depth,n): 5 if type(items) == int: 6 if type(items) == int: 7 if depth == n: 8 return 1
9 else: 10 return 0 11 else: 12 if (type(items) == tuple) or (type(items) == list): 13 result = 0 14 for i in range(len(items)): 15 result += getSum(items[i],depth+1,n) 16 return result 17 else: 18 return 0 19
20 items = eval(input()) 21 n = int(input()) 22 result = 0 23 for i in range(len(items)): 24 result = result + getSum(items[i],1,n) 25 print(result)