K
K
Kirill Pruntov2013-05-06 18:49:51
Python
Kirill Pruntov, 2013-05-06 18:49:51

Generating all possible distributions in a list?

Good afternoon! I'm new to Python (and programming in general) and I'm having a hard time creating a list generation function. I'm currently trying to do something similar to auto-predictions for portfolio investments and I need to create lists with all possible options for the distribution of shares between shares (excluding options when the shares are distributed among fewer shares), and the number of shares can be different.
As an example, I will give an option with 3 shares and a share step of 0.25:

1: |0.00|0.00|1.00|0.00|0.25|0.25|0.25|0.25|0.50|0.00|0.50|0.50|0.00|0.75|0.75|
2: |0.00|1.00|0.00|0.25|0.00|0.75|0.25|0.50|0.25|0.50|0.00|0.50|0.75|0.00|0.25|
3: |1.00|0.00|0.00|0.75|0.75|0.00|0.50|0.25|0.25|0.50|0.50|0.00|0.25|0.25|0.00|

I can't figure out how to generate similar lists for a different number of shares, for example, for 4:

Would be very grateful for the help!
UPD: Thanks again to Domini for reminding me that reading the documentation is more useful than asking stupid questions, I was able to solve my problem quite easily just by reading carefully, but I still have a question whether it is possible to increase performance, because the computer just hangs on generation.
here is the code:
from itertools import *

li = []

for i in count(0.00, 0.05):
    li.append(i)
    if i > 1.0:
        break

arr = []
for x in product(li, repeat=3):
    if sum(x) == 1.0:
        arr.append(x)
    else:
        pass

print arr

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Domini, 2013-05-06
@Domini

If I understand the question correctly, you just need to carefully read the manual page .

D
Domini, 2013-05-06
@Domini

In the forehead full lazy search with filtering itertools.ifilter(lambda x: sum(x) == 100, itertools.product(xrange(0, 101), repeat=3)) (for test output, wrap in list(... )).

V
Ventura, 2013-05-06
@Ventura

Recursion will save the father of Russian democracy.
General solution here - stackoverflow.com/questions/13131491/partition-n-items-into-k-bins-in-python-lazily
Private:

print [[sum(parts) for parts in subset] for subset in partition(list(itertools.repeat(1, 100)), 3)]

Hint: You will lose precision on floats.
Hint 2: For splitting into a large number of “shares”, it is better to rewrite to generators or reduce the step, otherwise there are many options.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question