0

i want to distribute amount of money to operators but after append for loop jumps not to another variable:

op1 = []
op2 = []
op3 = []
operators = [op1, op2, op3]
unsigned_loans = [100, 200, 300, 400]

sum_of_all_loans = 0

for loan in unsigned_loans:
    sum_of_all_loans += loan

per_user_amount = sum_of_all_loans / len(operators)

unsigned_loans.sort()



for oper in operators:
    for loan in unsigned_loans:
        print(loan)
        if sum(oper) < per_user_amount:
            oper.append(loan)
        unsigned_loans.remove(loan)
    print(oper)

output should be:

 op1=[100, 200] op2=[300] op3=[400]

but now it displays

op1=[100, 300] op2=[200] op3=[400]
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
I.Jokhadze
  • 456
  • 2
  • 8
  • 27
  • 1
    Please explain the logic behind your desired distribution. Currently you have just mentioned the code, which does what it is written for. How will we guess the logic behind your desired result? – Moinuddin Quadri Jan 30 '17 at 09:56

1 Answers1

4

You are iterating over a list and modifying it at the same time, this always invites errors. If you don't remove anything from the list in the loop, it will be more predictable. The immediate fix is to iterate over a copy, as the linked page suggests in the accepted answer.

Alternatively, you can tweak the logic a bit, e.g. always give loan to the operator with the lowest current sum:

for loan in unsigned_loans:
     oper = min(operators, key=sum)
     oper.append(loan)

This will result in [100, 400], [200], [300] in your case.

Community
  • 1
  • 1
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175