Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum the values of list to the power of their indices

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.

like image 510
BlueMoon93 Avatar asked Nov 16 '16 17:11

BlueMoon93


People also ask

How do you sum a list of strings in Python?

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.


2 Answers

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.

like image 194
Dimitris Fasarakis Hilliard Avatar answered Oct 26 '22 23:10

Dimitris Fasarakis Hilliard


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])
like image 31
P. Camilleri Avatar answered Oct 27 '22 00:10

P. Camilleri