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

How to sum list values ​​by 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. That way I can use a list to calculate the index of something.


Edit: while the question was answered, I just realized that the method does not create a unique index for any combination of non-negative integers in the list. For this, if a is the number of possible integers and is based on 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 ( 0 to 3 ), the above example becomes

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

If the indices will vary from 0 to 4^3-1=63 .

+5
source share
2 answers

Use enumerate to get the index and provide it sum :

 sum(j ** i for i,j in enumerate(l, 1)) 

Specifying the start argument to enumerate as 1 ensures that the indices begin with 1 (as you wish), and not from 0 (by default, which you get with a simple enumerate ):

 >>> l = [3, 0, 2] >>> sum(j ** i for i,j in enumerate(l, 1)) 11 

In a functional spirit, you can also use map with count from itertools , passing in pow as a function to display:

 >>> from itertools import count >>> sum(map(pow, l, count(1))) 11 

They are almost carried out at about the same time; the expression of the generator to sum , although it gives a slight advantage of flexibility.

+8
source

You can do this with numpy, which is often faster than repeating 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]) 
+1
source

Source: https://habr.com/ru/post/1259853/


All Articles