Home > Back-end >  Python dynamically incrementing sum
Python dynamically incrementing sum

Time:04-21

I've created a dictionary which gives me the sum from 0 to n/2 and all steps in between. n is an arbitrary even number, chosen to be 10 in this example.

n=10

dy = {}

for x in range(0,int(n/2)):
  dy["y{0}".format(x)] = 0

for x in range(1,int(n/2)):
  dy["y{0}".format(x)]  = dy["y{0}".format(int(x-1))]   x

print(dy)

So y0 = 0, y1 (=0 1) = 1 up to y4 (=0 1 2 3 4) = 10.

Now I need a very similar dictionary which gives the following (brackets not to be included, just to clarify calculation):

y0 = 1, y1 (=2 3) = 5, y2 (3 4 5) = 12, y3 (=4 5 6 7) = 22 and y4 (5 6 7 8 9) = 35.

Any ideas on how to achieve that?

Note: The calculation should be in principle as similar to the above example as the x is just a placeholder for an element of yet another dictionary in the actual code. So in the code the here called x actually looks more like dgr["gr{0}".format(x)].GetPointY(i).

CodePudding user response:

You can use range to achieve what you want. Try this:

n=10

dy = {}

for x in range(0,int(n/2)):
    dy["y{0}".format(x)] = 0

for x in range(0,int(n/2)):
    # Just change the line below to this: 
    dy["y{0}".format(x)]  = sum(range(x 1, 2*x   2))

print(dy)

Output:

{'y0': 1, 'y1': 5, 'y2': 12, 'y3': 22, 'y4': 35}

CodePudding user response:

If I understand the objective correctly then one way could be:

n = 10

def total(num):
    "Helper function to get sum of integers"
    return num * (num  1) // 2

first = {f"y{i}":total(i) for i in range(n//2)}
second = {f"y{i}": total(j)-first[f"y{i}"] for i, j in enumerate(range(1, n, 2))}

# first -> {'y0': 0, 'y1': 1, 'y2': 3, 'y3': 6, 'y4': 10}
# second -> {'y0': 1, 'y1': 5, 'y2': 12, 'y3': 22, 'y4': 35}

  • Related