Python: Sum a list of numbers
Python List: Exercise - 208 with Solution
Sum a list of numbers. Write a Python program to sum the first number with the second and divide it by 2, then sum the second with the third and divide by 2, and so on.
Equation: (element 0 + element 1) / 2, (element 1 + element 2) / 2, ... etc.
#Source: shorturl.at/csxLM def test(list1): result = [(x + y) / 2.0 for (x, y) in zip(list1[:-1], list1[1:])] return list(result) nums = [1,2,3,4,5,6,7] print("\nOriginal list:") print(nums) print("\nSum the said list of numbers:") print(test(nums)) nums = [0,1,-3,3,7,-5,6,7,11] print("\nOriginal list:") print(nums) print("\nSum the said list of numbers:") print(test(nums))
Original list: [1, 2, 3, 4, 5, 6, 7] Sum the said list of numbers: [1.5, 2.5, 3.5, 4.5, 5.5, 6.5] Original list: [0, 1, -3, 3, 7, -5, 6, 7, 11] Sum the said list of numbers: [0.5, -1.0, 0.0, 5.0, 1.0, 0.5, 6.5, 9.0]
Visualize Python code execution:
The following tool visualize what the computer is doing step-by-step as it executes the said program:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to find the common tuples between two given lists.
Next: Write a Python program to count the number of groups of non-zero numbers separated by zeros of a given list of numbers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Python: Tips of the Day
Decapitalizes the first letter of a string:
def tips_decapitalize(s, upper_rest=False): return s[:1].lower() + (s[1:].upper() if upper_rest else s[1:]) print(tips_decapitalize('PythonTips')) print(tips_decapitalize('PythonTips', True))
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook