Sum of Powers
Write sum_powers(*numbers, power=1) that returns the sum of each number raised to power.
sum_powers(1, 2, 3)is6.sum_powers(1, 2, 3, power=2)is14.- With no numbers it returns
0.
power can only be given by name: sum_powers(2, 3, 2) has three numbers and the default power.
Understand the problem
Predict how Python matches arguments to parameters.
Inside def f(*numbers, power=1), what is numbers when you call f(4, 5, 6)?
- A list
[4, 5, 6] - A tuple
(4, 5, 6) - The number 4
The extra positional arguments are collected into a tuple. A parameter after *numbers (here power) can only be set by name; it is keyword-only.
What is power for the call f(4, 5, 6)?
Positional arguments go into numbers. power keeps its default value 1, because it can only be given as power=....
What is the sum for sum_powers(2, 3, 2): remember 2 is a number here, not the power. Type the number.
The three numbers are 2, 3 and 2, and the power is the default 1: 2 + 3 + 2 = 7.
Write the solution
Keep the exact signature from the task.
def sum_powers(*numbers, power=1):
# Write your code here.
pass
Hint 1: a question to ask yourself
What type is numbers inside the function, and how do you go through it?
Hint 2: the shape of the answer
sum(n ** power for n in numbers). sum of an empty generator is 0.
Reflect
Solution
def sum_powers(*numbers, power=1):
return sum(n ** power for n in numbers)
What this tests: *args (variable positional arguments), keyword-only parameters, and a generator expression with sum.
The four kinds of parameters, in the order they must appear: normal, *args, keyword-only (after *args or a bare *), **kwargs. A bare * makes the following parameters keyword-only without collecting anything: def f(a, *, flag=False).
Why keyword-only: a call like connect(host, 5, True) is unreadable. Forcing connect(host, retries=5, verbose=True) makes calls self-explanatory. Use it for options.
Calling with a list: sum_powers(*[1, 2, 3], power=2) unpacks the list into separate arguments.
Cost: O(n).
What an interviewer might ask next: What is the difference between def f(a, b=[]) and def f(a, *, b=None)? (The first has the mutable default trap; the second is keyword-only and safe.)
VISIBLE = 3
CASES = [
('result = sum_powers(1, 2, 3)', 6, 'no power given'),
('result = sum_powers(1, 2, 3, power=2)', 14, 'power by name'),
('result = sum_powers()', 0, 'no numbers at all'),
('result = sum_powers(2, 3, 2)', 7, 'a last number is not the power'),
('result = sum_powers(5, power=0)', 1, 'power zero'),
('result = sum_powers(2, 3, power=3)', 35, 'cubes'),
('result = sum_powers(-2, 2, power=2)', 8, 'negative numbers'),
('result = sum_powers(*[1, 2, 3], power=2)', 14, 'unpacking a list'),
]