3

Say you have n items each ranging from 1-100. How can I get go over all possible variations within the range?

Example:

3 stocks A, B and C

Working to find possible portfolio allocation.

A - 0     0   0            1    2          1    1
B - 0     1   2      ...   0    0    ...   1    2
C - 100   99  98           99   98         98   97

Looking for an efficient way to get a matrix of all possible outcomes.

Sum should add up to 100 and cover all possible variations for n elements.

6
  • 1
    This is a pretty unclear question... Are you saying that you want all permutations of three numbers between 1 and 100 such that the sum of the three equals 100? Commented Sep 8, 2016 at 21:33
  • 1
    @mgilson Yes, that is correct. I'll update question. Looking for an efficient way to handle it though. And for n numbers, obviously Commented Sep 8, 2016 at 21:34
  • 3SUM problem in non-zero sum variant? Commented Sep 8, 2016 at 21:39
  • This sounds like you're trying to brute-force a problem that would be better solved by getting a more sophisticated library for it. Commented Sep 8, 2016 at 21:43
  • 1
    I think your problem has an answer here stackoverflow.com/questions/13988197/…. Commented Sep 8, 2016 at 21:47

1 Answer 1

2

How I'd do it:

>>> import itertools
>>> cp = itertools.product(range(101),repeat=3)
>>> portfolios = list(p for p in cp if sum(p)==100)

But that creates unnecessary combinations. See discussions of integer partitioning to avoid that. E.g., Elegant Python code for Integer Partitioning

Sign up to request clarification or add additional context in comments.

3 Comments

This is O(N^3) -- It'll take a million iterations when you should be able to come up with a solution in about 5000 iterations (for N = 100).
The amount-of-used-code-lines efficiency is great.
@mgilson Agreed. That's why I provided the link for integer partitioning.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.