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.

James Raitsev
  • 92,517
  • 154
  • 335
  • 470
  • 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? – mgilson Sep 08 '16 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 – James Raitsev Sep 08 '16 at 21:34
  • [3SUM problem](https://en.wikipedia.org/wiki/3SUM) in non-zero sum variant? – Łukasz Rogalski Sep 08 '16 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. – user2357112 Sep 08 '16 at 21:43
  • Maybe use numpy for the matrix presentation? http://stackoverflow.com/questions/17870612/printing-a-two-dimensional-array-in-python – Tom Pitts Sep 08 '16 at 21:45
  • 1
    I think your problem has an answer here http://stackoverflow.com/questions/13988197/how-to-iterate-through-array-combinations-with-constant-sum-efficiently. – Rockybilly Sep 08 '16 at 21:47

1 Answers1

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

Community
  • 1
  • 1
Alan
  • 9,410
  • 15
  • 20