-1

I have to create an array in Python with random elements, random numbers of elements. The only important thing is that: the sum of all elements should be equal to 1024

Examples: range of elements min=1, max=1024, sum=1024.

  1. case: [1000, 13, 11], 3 elements, their sum is 1024.
  2. case: [500, 200, 100, 2, 22, 150, 50], 7 elements, their sum is 1024.

It doesn't matter if there are identical number [512, 512]. Can someone explain me how to do that?

Liam
  • 6,009
  • 4
  • 39
  • 53

1 Answers1

0

here it is:

input:

import random
b =[]
a = 0
c = 0
d = 1024
while True:
    a = random.randint(1,d)
    c = c + a
    if c<1024:
        b.append(a)
    else:
        a = 1024 - c +a
        b.append(a)
        break
print b

output:

b = [29, 473, 292, 230] = 1024

(lower "d" equals to a longer "b" list)

Liam
  • 6,009
  • 4
  • 39
  • 53
  • @NicolaCurrò is the size of `b` (4) equal to sum of elements (1024)? – marmeladze May 09 '15 at 16:17
  • @marmeladze yes it is: 29+473+292+230 = 1024 – Liam May 09 '15 at 16:21
  • "the size should be equal to the sum of all elements". as i understand for `A = (a_1, a_2, a_3 ... a_n)`. size (`len(A)`) is `n`. sum of elements (`sum(A)`) is `a_1+a_2+a_3+...a_n`. are they equal? i'm just curious of, if @NicolaCurrò had expressed himself clearly. – marmeladze May 09 '15 at 16:26
  • @marmeladze yes, size= a_1+a_2+a_3+a_4+....a_n – Nicola Currò May 10 '15 at 16:23