-1

Given a list containing integers :

>>> print mylist
[0, 1, 2]

Can I calculate the sum of 2^0 + 2^1 + 2^2 ? the base number (2) is fixed, it does not change, I'm just using the elements of list as exponents

related doubts :

Is a list suitable for what I'm trying to do?

Community
  • 1
  • 1
lese
  • 539
  • 1
  • 5
  • 24

6 Answers6

5

Of course it is.

mylist = [0, 1, 2]
print sum([2**x for x in mylist])

Output:

7
Avión
  • 7,963
  • 11
  • 64
  • 105
  • 2
    Use this one, not the other answers with `^` instead of `**`. `^` performs a bit-wise exclusive or (xor). For instance, 2 ^ 2 == 0 (binary 10 xor 10 == 00) and 2 ^ 1 == 3 (binary 10 xor 01 == 11). – Colin Oct 30 '15 at 11:16
  • @Colin good point, didn't realize about that. Funny thing is that I wrote output 5 and all the others wrote 5 too... damn those copy&paste xDDD –  Oct 30 '15 at 11:22
  • 1
    You can also use `sum(2**x for x in my list)`; you don't to build a list object just to pass to `sum`. – chepner Oct 30 '15 at 12:22
2
mylist = [0,1,2]
mysum = 0
for i in mylist:
    mysum = mysum + 2**i


>>> print mysum
7
1

You may simply use map() and lambda expression as :

print sum(map(lambda x:2**x, mylist))
>>> 7
ZdaR
  • 22,343
  • 7
  • 66
  • 87
  • 1
    Passing a user-defined function to `map` is generally less efficient than simply using a list comprehension. – chepner Oct 30 '15 at 12:23
0

I guess you could use a list, but, given the linear nature of its elements, it'd probably be better to just use a range() object:

mynum = 2
mysum = sum(2**x for x in range(mynum+1))
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
  • 1
    You're assuming the list is contiguous; what about `mylist = [ 0, 3, 5, 7]`? – chepner Oct 30 '15 at 12:24
  • The list in the example _is_ contiguous (linear, anyway - `range(0, 10, 3)` is discontiguous but linear). That's why I suggested `range()`. I figured there was a good chance that the OP's use cases involved such a pattern. If more information was provided that revealed the use of non-linear `list`s, that would be different. – TigerhawkT3 Oct 30 '15 at 12:28
0

an alternate way of doing this without using list is :

x=0 for i in range(0,3): x= x + pow(2,i) print "%d" % x

-3

Try

mylist = [0,1,2]
sum(2**i for i in mylist)
Stephan W.
  • 188
  • 13