Dada una tupla anidada en la 2.ª posición, devuelve la suma de los 1.er elementos.
Entrada : test_tup = (5, (6, (1, (9, Ninguno))))
Salida : 21
Explicación : 9 + 6 + 5 + 1 = 21.Entrada : test_tup = (5, (6, (1, Ninguno)))
Salida : 12
Explicación : 1 + 6 + 5 = 12.
Método #1: Usar bucle infinito
En esto, realizamos entrar en la estructura sesgada mientras sumamos usando un ciclo infinito y rompemos cuando alcanzamos el valor Ninguno.
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))
Producción
The original tuple is : (5, (6, (1, (9, (10, None))))) Summation of 1st positions : 31
Método #2: Usar recursividad
En esto, realizamos la suma y recurrimos para el segundo elemento de la tupla, regresamos a Ninguno.
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))
Producción
The original tuple is : (5, (6, (1, (9, (10, None))))) Summation of 1st positions : 31
Publicación traducida automáticamente
Artículo escrito por manjeet_04 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA