Home > Net >  How compute "for-loop" sum of n numbers equals 1?
How compute "for-loop" sum of n numbers equals 1?

Time:12-21

I want to set up a for loop but the loop must satisfy the following special conditions:

  1. n: number of loops, and there should be n float results.
  2. The sum of n float results must be 1. (X1 X2 ... Xn = 1)
  3. each new result should decrease by halving.

For example:

n=1             x=1
n=2             x1=0.5 , x2=0.5
n=3             x1=0.5 , x2=0.25, x3=0.25
n=4             x1=0.5 , x2=0.25, x3=0.125, x4=0.125

I could not formulate the problem mathematically.

CodePudding user response:

In every iteration, get the last element of your list, halve it, and append the halved value back to the list.

lst = [1]
for _ in range(n-1):
    e = lst[-1]
    lst[-1] = e/2
    lst.append(e/2)

print(lst)
# [0.5, 0.25, 0.125, 0.125]

Try online

We only need to iterate n-1 times because we started off with 1 already in the list.

  • Related