📜  Python – 倾斜嵌套元组求和

📅  最后修改于: 2022-05-13 01:55:49.483000             🧑  作者: Mango

Python – 倾斜嵌套元组求和

给定一个嵌套在第二个位置的元组,返回第一个元素的总和。

方法#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