How do I sum the values of list to the power of their indices in Python 3
?
Example:
[3, 0, 2] = 3^1 + 0^2 + 2^3 = 11
The idea is to create a unique index for any possible combination of non-negative numbers in the list. This way, I can use the list to compute an index of something.
Edit: while the question has been answered, I just realized that the method does not create a unique index for any combination of non-negative integers in the list. To do so, assuming a
is the number of possible integers, and based in the accepted answer,
sum(a ** i * j for i,j in enumerate(l, 0))
The idea is that each number will increase the index by an amount exponentially proportional to its position in the list. Assuming a=4
(from 0
to 3
), the above example becomes
[3, 0, 2] = 4^0*3 + 4^1*0 + 4^2^2 = 35
Where the indices would range from 0
to 4^3-1=63
.
Use type() and isdigit() functions in Python to achieve a sum list of strings in Python. This function will check If the element is int, then add it to the total by checking two conditions.
Use enumerate
to get the index and supply that to sum
:
sum(j ** i for i,j in enumerate(l, 1))
Specifying the start
argument to enumerate
as 1
assures indices will start from 1
(as you want) and not from 0
(the default which you get with a plain enumerate
):
>>> l = [3, 0, 2]
>>> sum(j ** i for i,j in enumerate(l, 1))
11
In a functional spirit, you could also utilize map
with count
from itertools passing in pow
as the function to be mapped:
>>> from itertools import count
>>> sum(map(pow, l, count(1)))
11
These pretty much execute in approximately the same time; the generator expression to sum
though offers a slight advantage of flexibility.
You can do this with numpy, which is often faster than iterating through lists:
In [1]: import numpy as np
In [2]: l = [0, 3, 4, 1]
In [3]: np.array(l) ** np.arange(len(l))
Out[3]: array([ 1, 3, 16, 1])
In [4]: np.array(l) ** np.arange(1, len(l) + 1)
Out[4]: array([ 0, 9, 64, 1])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With