Search code examples
pythonlistfor-loopreverseenumerate

Python creating specific list from another list


Learning python I encountered the following problem. I already have some list with integer numbers (for example initial_list). Then I'm trying to create list (for example result) with following numbers pattern:

result[len(result) - 1] = 1
result[i] = result[i + 1] * initial_list[i]

Example:

initial_list = [2, 2, 2, 2, 3, 2, 2]
result = [192, 96, 48, 24, 12, 4, 2, 1]

Here is my first implementation:

import numpy as np
initial_list = [2, 2, 2, 2, 3, 2, 2]
result = [1]
for number in reversed(initial_list):
    result.append(result[-1] * number)
result = np.array(result[::-1])

Here is my second implementation:

import numpy as np
initial_list = [2, 2, 2, 2, 3, 2, 2]
result = np.ones(len(initial_list) + 1)
for i, number in enumerate(reversed(initial_list)):
    result[len(result) - i - 2] = result[len(result) - i - 1] * number

I guess second one is much better because it does not contain append method and initialize list with concrete size. Also result = np.ones(len(initial_list) + 1) consists with float point number which is not correct. I wonder whether there is a simpler version of the implementation of this algorithm.

After that algorithm I'm creating OrderedDict:

from collections import OrderedDict
ordered_dict = OrderedDict(zip(other_list, result))

Maybe I can reverse result list during creating OrderedDict for O(1) "on fly" like reversed works in for looping, so that I can simplify algorithm above.


Solution

  • If numpy is an option, you can do it with cumprod:

    import numpy as np
    
    initial_list = [2, 2, 2, 2, 3, 2, 2]
    
    >> np.append(np.cumprod(initial_list[:: -1])[:: -1], [1])
    array([192,  96,  48,  24,  12,   4,   2,   1])