Sum of variabels from each for loop iterations

42 views Asked by At

I want to solve this exercise https://www.codewars.com/kata/5648b12ce68d9daa6b000099/train/python enter image description here

How can I count result of count variable from first and second loop together ? Result from first loop is 4-2 = 2, now I want sum of the 2 + result from second loop 10-6= 4. So the total sum should be 6 . Thanks for your tips :)

array =[(4,2), (10,6)]
print((array))
print(array[1])

for x in array:
    count = (x[0] - x[1])
    print (count)

I am not sure if this process is good for the exercise but I want it try this way :)

Thanks :)

1

There are 1 answers

2
JANO On

your approach doesn't look too bad. Iterating over the bus stop to find the difference of people leaving and joining the bus. You only have to add one variable that adds up these differences. I called it counter, which counts the current number of people on the bus. It starts with a value of zero. Then in each iteration, we add the difference to the counter variable. If more people leave the bus than enter it the counter will be decreased as current_difference is negative. Here is an example implementation:

array =[(4,2), (10,6)]

counter = 0
for x in array:
    current_difference = (x[0] - x[1])
    print (current_difference)
    counter = counter + current_difference
    
print(counter)

Result:

6