Multiply number list by range of numbers
<p>I'm trying to write code for a modulus 11 but I'm failing to make it more python-like.</p>

<p>As of now I'm using a weight and increasing it, checking when it reaches a number and then set it to it's original value.</p>

<p>Let's say I have a list of numbers
<code>1..20</code> and I'd like to multiply them by <code>2,3,4,5,6,7,8,9,2,3,4,etc</code> so that each index would be multiplied by an increasing number.</p>

<p>1x2, 2x3, 3x4, 4x5, 5x6, 6x7, 7x8, 8x9, 9x2, 10x3, etc..</p>

<p>Is there an elegant way to do this?</p>

<p>Unelegant way:</p>

<pre><code>def mod11(list, max_weight=9):
    sum = 0
    weight = 2

    for item in reversed(list):
        sum += item * weight
        weight += 1

        if weight &gt; max_weight:
            weight = 2

    mod = 11 - sum % 11

    if mod &gt; 9:
        return 0

    else:
        return mod
</code></pre>

<p>A lot of good answers here already, and in case you would like to use <code>numpy</code> (usually good for this sort of thing), here's an alternative:</p>

<pre><code>In [1]: import numpy as np

In [2]: a = np.arange(1, 21)  # like range in numpy array

In [3]: a - 1  #Â calculation performs per element wise... so will a * n
Out[3]:
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19])


In [4]: a * ((a - 1) % 8 + 2)  # directly translate the calculation
Out[4]:
array([  2,   6,  12,  20,  30,  42,  56,  72,  18,  30,  44,  60,  78,
        98, 120, 144,  34,  54,  76, 100])
</code></pre>

python