Python: Sum of the magnitudes of the elements in the array with product signs
Python Programming Puzzles: Exercise-57 with Solution
Write a Python program to find the sum of the magnitudes of the elements in the array. This sum should have a sign that is equal to the product of the signs of the entries.
Input: [1, 3, -2] Output: -6 Input: [1, -3, 3] Output: -7 Input: [10, 32, 3] Output: 45 Input: [-25, -12, -23] Output: -60
Pictorial Presentation:

Sample Solution:
Python Code:
def test(nums):
tot = sum(abs(i) for i in nums)
if all(nums):
return tot if sum(i < 0 for i in nums) % 2 == 0 else -tot
return 0
nums = [1, 3, -2]
print("Original list of numbers:")
print(nums)
print("Sum of the magnitudes of the elements in the array with a sign that is equal to the product of the signs of the entries:")
print(test(nums))
nums = [1, -3, 3]
print("\nOriginal list of numbers:")
print(nums)
print("Sum of the magnitudes of the elements in the array with a sign that is equal to the product of the signs of the entries:")
print(test(nums))
nums = [10, 32, 3]
print("\nOriginal list of numbers:")
print(nums)
print("Sum of the magnitudes of the elements in the array with a sign that is equal to the product of the signs of the entries:")
print(test(nums))
nums = [-25, -12, -23]
print("\nOriginal list of numbers:")
print(nums)
print("Sum of the magnitudes of the elements in the array with a sign that is equal to the product of the signs of the entries:")
print(test(nums))
Sample Output:
Original list of numbers: [1, 3, -2] Sum of the magnitudes of the elements in the array with a sign that is equal to the product of the signs of the entries: -6 Original list of numbers: [1, -3, 3] Sum of the magnitudes of the elements in the array with a sign that is equal to the product of the signs of the entries: -7 Original list of numbers: [10, 32, 3] Sum of the magnitudes of the elements in the array with a sign that is equal to the product of the signs of the entries: 45 Original list of numbers: [-25, -12, -23] Sum of the magnitudes of the elements in the array with a sign that is equal to the product of the signs of the entries: -60
Flowchart:

Python Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Find an integer exponent x such that a^x = n.
Next: Biggest even number between two numbers inclusive.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join