Reputation: 10142
The beauty of python
is often reflected in its simplicity and one-liner codes.
I am slowly getting myself in writing them.
I have a function that calculates the sum of n
powers of 2.
ex: if n==4, I get 2^4+2^3+2^2+2^1+2^0
I have this function which works fine, but wondering if there is room for condensing to one or two lines
>>> def sumpowers(n):
... sum=0
... for x in range(n+1):
... sum+=pow(2,x)
... return sum
...
>>> sumpowers(31)
4294967295
Any tips or some use of built-ins
that can improve it in terms of simplicity?
Thanks
Upvotes: 2
Views: 166
Reputation: 31252
using reduce built-in
and lambda, you could achieve it:
>>> reduce(lambda x,y: x+y, [pow(2,i) for i in range(32)])
4294967295
in terms of function:
try this:
>>> def test(n):
... return reduce(lambda x,y: x+y,[pow(2,i) for i in range(n+1)])
...
>>> test(31)
4294967295
EDIT: using reduce
is absolutely not necessary. as pointed out in the comments, it might not often be a good idea. but it is an aspect of functional programming that could be made of use and is one of several ways pointed out
Upvotes: 0
Reputation: 236004
Try this solution, is more idiomatic:
def sumpowers(n):
return sum(2**x for x in range(n+1))
The "trick" to make it more concise lies in using the following:
sum
built-in function, instead of a counter variable**
operator, instead of the pow
built-in function (the two are equivalent when using two arguments)But wait! we can make things even simpler by using mathematical properties. The function is equivalent to this (with kudos to @fp for pointing it out first):
def sumpowers(n):
return 2**(n+1)-1
Either way, it works as expected:
sumpowers(31)
=> 4294967295
Upvotes: 2
Reputation: 11468
Nothing is better in this case than list comprehension.
my_sum=sum([2**x for x in range(n+1)])
Upvotes: 2
Reputation:
That for-loop can be replaced with the sum
built-in and a generator expression:
>>> def sumpowers(n):
... return sum(pow(2,x) for x in range(n+1))
...
>>> sumpowers(31)
4294967295
>>>
You may also want to replace pow(2,x)
with just 2**x
:
>>> def sumpowers(n):
... return sum(2**x for x in range(n+1))
...
>>> sumpowers(31)
4294967295
>>>
Upvotes: 3
Reputation: 11531
Try the following:
def sumpowers(n):
return ((2 ** (n+1)) - 1)
Upvotes: 3