In the same file, write a function sum_of_product that takes in a list of tuples and returns the sum of the product of the elements in each tuple. Each tuple always contains two elements. Example: sum_of_product([(1,2),(3,4)]) = 14 sum_of_product([]) = 0
时间: 2024-04-16 11:29:27 浏览: 123
Certainly! Here is the implementation of the `sum_of_product` function:
```python
def sum_of_product(tuple_list):
total = 0
for tuple in tuple_list:
product = tuple[0] * tuple[1]
total += product
return total
```
The `sum_of_product` function takes in a list of tuples, `tuple_list`. It initializes a variable `total` to keep track of the sum of the products. It then iterates over each tuple in `tuple_list`. For each tuple, it calculates the product of its two elements and adds it to the `total`. Finally, it returns the `total` as the result.
Here are a few examples of using the `sum_of_product` function:
```python
print(sum_of_product([(1, 2), (3, 4)])) # Output: 14
print(sum_of_product([])) # Output: 0
```
In the first example, it calculates the product of `(1, 2)` and `(3, 4)` which results in `2 + 12 = 14`. In the second example, as the input list is empty, it returns `0` as there are no tuples to calculate the product from.
阅读全文