w3resource

Python: Sum of all items of a given array of integers where each integer is multiplied by its index

Python Basic - 1: Exercise-100 with Solution

Write a Python program to compute the sum of all items in a given array of integers where each integer is multiplied by its index. Return 0 if there is no number.

Sample Solution:

Python Code:

# Define a function named sum_index_multiplier that takes a list of numbers (nums) as an argument.
def sum_index_multiplier(nums):
    # Use a generator expression within the sum function to calculate the sum of each element multiplied by its index.
    # The expression j*i for i, j in enumerate(nums) iterates over the elements and their indices.
    return sum(j * i for i, j in enumerate(nums))

# Test the function with different lists of numbers and print the results.

# Test case 1
print(sum_index_multiplier([1,2,3,4]))

# Test case 2
print(sum_index_multiplier([-1,-2,-3,-4]))

# Test case 3
print(sum_index_multiplier([]))

Sample Output:

20
-20
0

Explanation:

Here is a breakdown of the above Python code:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/basic/python-basic-1-exercise-100.php