Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sum each value in a list to all previous values including extra value between them

im trying to add the value of each element in a list to all previous values without using numpy of any other library.
the list (dis) represent the length of elements which i need to calculate their positions if i want to place them and have 100 mm distance between each of them.

the first element i want it to be placed at 0
i have tried the following:

dis = [40,400,20,100,400]
betweenDistance = 100
_dis = []

total = 0

for e,x in enumerate(dis):
    if e == 0:
        _dis.append(0)
    elif e < (len(dis)-1):
        _dis.append( total + ((dis[e-1])/2) + betweenDistance + (x/2) )
        total+=(sum(_dis[0:e]))
    else:
        _dis.append((x/2)+betweenDistance+total)
        

OUT = _dis

what i need to have in the end is the following:
0, 320, 630, 790, 1140

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try defining a helper function with a for loop:

def calculate_positions(elements: list[int], gap_distance: int) -> list[int]:
  """Calculate element positions based on their lengths and a set gap distance."""
  positions = [0]
  for i in range(1, len(elements)):
    prev_position = positions[-1]
    prev_element_length = elements[i - 1]
    current_element_length = elements[i]
    new_position = int(prev_position + (prev_element_length / 2) +
                       gap_distance + (current_element_length / 2))
    positions.append(new_position)
  return positions

print(f'{calculate_positions(elements=[40, 400, 20, 100, 400], gap_distance=100) = }')

Output:

calculate_positions(elements=[40, 400, 20, 100, 400], gap_distance=100) = [0, 320, 630, 790, 1140]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading