Write a Python program to Skew Nested Tuple Summation


The program is written in Python and performs the following operations:

  • Defines a nested tuple called "val".
  • Prints the nested tuple.
  • Defines a variable "res" and initializes it to 0.
  • Starts a while loop, which will keep running until the tuple "val" is empty.
  • Within the while loop, the current value of "val[0]" is added to the "res" variable.
  • The tuple "val" is then assigned to "val[1]" so that the next iteration of the while loop will access the next nested tuple.
  • The while loop continues until "val" is empty, at which point the loop stops.
  • Prints the sum of all first positions of the nested tuples.

The final output of the program will be the sum of all the first positions of the nested tuples. The while loop will keep accessing the first position of the current nested tuple, adding it to the "res" variable, and then moving to the next nested tuple until there are no more nested tuples.

Source Code

val = (1, (2, (3, (4, (5, None)))))
 
print("Tuple : ",val)
 
res = 0
while val:
	res += val[0]
	val = val[1]
 
print("Summation of 1st positions : " ,res)

Output

Tuple :  (1, (2, (3, (4, (5, None)))))
Summation of 1st positions :  15

Example Programs