Answer the question
In order to leave comments, you need to log in
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|
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
If I understand the question correctly, you just need to carefully read the manual page .
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(... )).
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)]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question