WhitneyChia - 6 months ago 30

Python Question

So the gist of this is a function that takes two sorted lists. It takes a list of negative numbers (people who owe money) and a list of positive number (people who are owed money). It then pays off the people who are owed money from the negative list.

Example:

`negatives = [-55.774, -45.884, -40.754, -35.694, -33.734, -29.024, -25.114, -16.144, -14.014, -5.874, -5.554]`

positives = [43.936, 42.276, 33.756, 31.116, 30.456, 27.616, 21.526, 18.276, 13.176, 12.376, 11.966, 8.566, 8.486, 4.036]

The first step in my process is negatives[0] will pay off the positives[0], 43.936, then it pays off partially positives[1] until itself negatives[0] is 0, it then moves onto negatives[1] and pays off what is owed to positives[1]. I'm just trying to iterate this process. Here's what I have:

`def pay_balances(x, y):`

i = 0

j = 0

while i < len(x) and j < len(y):

while abs(x[i]) > abs(y[j]) and abs(round(x[i],4)) != 0:

print y[j]

x[i] = x[i] + y[j]

y[j] = 0

j += 1

print i, j

while abs(x[i]) < abs(y[j]) and abs(round(x[i],4)) != 0:

print -x[i]

y[j] = y[j] + x[i]

x[i] = 0

i += 1

print i, j

So, if you run...

`pay_balances(negatives, positives)`

This will eventually break due to IndexError: list index out of range

The issue is when we are the end of the lists, and my j value = 14 which is when I want everything to stop. It appears to stay in the loop even though I have this line which I thought would kill it:

`while i < len(x) and j < len(y):`

What am I doing wrong? As always thanks a lot!!

Answer

Since you increment the indices `i`

and `j`

in the inner loops, you need to put the corresponding condition also in the first inner `while`

loop, and add an exit point half-way:

```
while i < len(x) and j < len(y):
while j < len(y) and abs(x[i]) > abs(y[j]) and abs(round(x[i],4)) != 0:
print y[j]
x[i] = x[i] + y[j]
y[j] = 0
j += 1
print i, j
if j >= len(y):
break
while i < len(x) and abs(x[i]) < abs(y[j]) and abs(round(x[i],4)) != 0:
print -x[i]
y[j] = y[j] + x[i]
x[i] = 0
i += 1
print i, j
```

Source (Stackoverflow)