Understanding the Summation Problem
00:00 Understanding The Summation Problem. Summing numeric values together is a fairly common problem in programming. For example, let’s say you have a list of numbers and want to add them together to compute their total sum. With standard arithmetic, you do something like this.
00:17 As far as the math goes, this expression is fairly straightforward. It walks you through a short series of additions until you find the sum of all the numbers. It’s possible to do this particular calculation by hand, but you can imagine some other situations where it wouldn’t be.
00:33 If you have a particularly long list of numbers, adding by hand can be inefficient and error-prone. What happens if you don’t even know how many items are in the list? Finally, imagine a scenario where the number of items you need to add changes dynamically or unpredictably. In situations like these, whether you have a long or short list of numbers, Python can be quite useful to solve summation problems.
This way, you can reuse the code for different lists. In
sum_numbers(), you take an iterable as an argument, specifically a list of numeric values, and you return the total sum of the values in the input list.
02:03 You can also use recursion instead of iteration. Recursion is a functional programming technique where a function is called within its own definition. In other words, a recursive function calls itself in a loop.
When you define a recursive function, you take the risk of running into an infinite loop. To prevent this, you need to define both a base case that stops the recursion and a recursive case to call the function and start the implicit loop. Here, the base case implies that the sum of a zero-length list is
Another option to sum a list of numbers in Python is to use
functools. To get the sum of a list of numbers, you can pass either
operator.add or an appropriate
lambda function as the first argument to
reduce(). You call reduce with a reduction, or folding, function along with an iterable as arguments.
Appropriately, the function is called
sum(). As it’s a built-in function, you can use it directly in your code without importing anything, and you’ll start doing exactly that in the next section of the course.
Become a Member to join the conversation.