Chapter 8 Tuples

8.2 Problem Solving by Traversal of a TupleΒΆ

The for loop can be used to solve all the basic problems introduced earlier, including summation, production, maximum finding and search, all by traversal of a container object. The following example illustrates the use of a for loop for summing up all elements in a tuple.

The for statement above iterates through t, assigning to x the value of the current element being enumerated at each iteration. Summation is performed by accumulating all x values to the sum s, which is initialized to 0. The thinking behind the method is the same as the summation using a while loop introduced earlier.

For summation, Python provides a built-in function sum, which takes a single iterable argument and returns the sum of all elements in the container object. Using the sum function, the example above can be written as:

In similar spirit, Python provides two built-in functions max and min, which take a single iterable argument and return the maximum and minimum elements in the container object, respectively.

The following code illustrates the use of a for loop to find the maximum value of a tuple. The thinking behind is the same as finding a maximum value using a while loop.

The problem above can also be solved using the function call max(t).

The following code illustrates the use of a for loop to decide whether there is a multiple of 7 in a tuple of integers. The thinking behind is the same as searching for a target using a while loop.

© Copyright 2024 GS Ng.

Next Section - 9.1 Lists - A Mutable Sequential Type