Python – 倾斜嵌套元组求和
给定一个嵌套在第二个位置的元组,返回第一个元素的总和。
Input : test_tup = (5, (6, (1, (9, None))))
Output : 21
Explanation : 9 + 6 + 5 + 1 = 21.
Input : test_tup = (5, (6, (1, None)))
Output : 12
Explanation : 1 + 6 + 5 = 12.
方法#1:使用无限循环
在这种情况下,我们在使用无限循环求和时执行 get into skew structure,并在达到 None 值时中断。
Python3
# Python3 code to demonstrate working of
# Skew Nested Tuple Summation
# Using infinite loop
# initializing tuple
test_tup = (5, (6, (1, (9, (10, None)))))
# printing original tuple
print("The original tuple is : " + str(test_tup))
res = 0
while test_tup:
res += test_tup[0]
# assigning inner tuple as original
test_tup = test_tup[1]
# printing result
print("Summation of 1st positions : " + str(res))
Python3
# Python3 code to demonstrate working of
# Skew Nested Tuple Summation
# Using recursion
# helper function to perform task
def tup_sum(test_tup):
# return on None
if not test_tup:
return 0
else:
return test_tup[0] + tup_sum(test_tup[1])
# initializing tuple
test_tup = (5, (6, (1, (9, (10, None)))))
# printing original tuple
print("The original tuple is : " + str(test_tup))
# calling fnc.
res = tup_sum(test_tup)
# printing result
print("Summation of 1st positions : " + str(res))
输出
The original tuple is : (5, (6, (1, (9, (10, None)))))
Summation of 1st positions : 31
方法#2:使用递归
在此,我们对元组的第二个元素执行求和和递归,返回 None。
Python3
# Python3 code to demonstrate working of
# Skew Nested Tuple Summation
# Using recursion
# helper function to perform task
def tup_sum(test_tup):
# return on None
if not test_tup:
return 0
else:
return test_tup[0] + tup_sum(test_tup[1])
# initializing tuple
test_tup = (5, (6, (1, (9, (10, None)))))
# printing original tuple
print("The original tuple is : " + str(test_tup))
# calling fnc.
res = tup_sum(test_tup)
# printing result
print("Summation of 1st positions : " + str(res))
输出
The original tuple is : (5, (6, (1, (9, (10, None)))))
Summation of 1st positions : 31