w3resource

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


Sum of Items Weighted by Index

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:

  • Function definition:
    • The code defines a function named "sum_index_multiplier()" that takes a list of numbers (nums) as an argument.
  • Generator Expression and Enumerate:
  • The function uses 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 Statement:
    • The function returns the result of the sum operation.

    Visual Presentation:

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


    Flowchart:

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


    For more Practice: Solve these Related Problems:

    • Write a Python program to compute the weighted sum of a list of integers, where each element is multiplied by its index.
    • Write a Python program to calculate the sum of products of each element in an array with its corresponding index using list comprehension.
    • Write a Python program to determine the weighted sum of items by iterating with enumerate over the list.
    • Write a Python program to compute the sum of list items multiplied by their indices and return 0 if the list is empty.

    Go to:


    Previous: Write a Python program to find the position of the second occurrence of a given string in another given string.
    Next: Write a Python program to find the name of the oldest student from a given dictionary containing the names and ages of a group of students.

    Python Code Editor:

    Have another way to solve this solution? Contribute your code (and comments) through Disqus.

    What is the difficulty level of this exercise?

    Test your Programming skills with w3resource's quiz.

    

    Follow us on Facebook and Twitter for latest update.