BlueMoon93 - 6 months ago 29

Python Question

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

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`

`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`

`0`

`3`

`[3, 0, 2] = 4^0*3 + 4^1*0 + 4^2^2 = 35`

Where the indices would range from

`0`

`4^3-1=63`

Answer

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):

```
>>> 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
```