0

I am having a strange problem in Python. I have the following code:

    for cd in self.current_charging_demands:
        print"EV{}".format(cd.id)

    # Check the value of SOC.
    for cd in self.current_charging_demands:
        print"EV{}, Current SOC: {}, required power: {}, allocated power: {}, max power: {}\n".format(cd.id, round(cd.battery.current_soc, 2), cd.battery.power_to_charge, cd.battery.allocated_powers, cd.battery.max_power)
        if round(cd.battery.current_soc, 2) >= cd.battery.desired_soc:
            #print"EV{} - current SOC: {}".format(cd.id, cd.battery.current_soc)
            result.append(cd)
            db.delete_charging_demand(self.current_charging_demands, cd.id)

The first for is printing these values:

EV1
EV2
EV5
EV4 

The second one is printing these:

EV1, Current SOC: 0.44, required power: 15.1, allocated power: 0.15638636639, max power: 3.3

EV2, Current SOC: 0.9, required power: 1.0, allocated power: 1.0, max power: 1.0

EV4, Current SOC: 0.92, required power: 6.5, allocated power: 3.3, max power: 3.3

As you can see, one value (EV5) is missing in the second for, and I really can't explain why. The for is done on the same object, which has not been modified between both loop. On the next call of these function, I am getting the following values:

EV1
EV5
EV4

for the first loop and:

EV1, Current SOC: 0.44, required power: 15.0, allocated power: 0.15638636639, max power: 3.3

EV5, Current SOC: 0.35, required power: 23.7, allocated power: 0.0, max power: 3.3

EV4, Current SOC: 0.92, required power: 3.2, allocated power: 0.0, max power: 3.2

Any idea on what is happening ?

Thank you very much.

Ecterion
  • 161
  • 3
  • 19

1 Answers1

3

In your code there is a line

db.delete_charging_demand(self.current_charging_demands, cd.id)

You should be very careful when deleting an element during iterating. Some elements may be skipped.

To see this, try running the following code.

a = [1, 2, 3, 4]
for x in a:
    print(x)
    if x == 2:
        a.remove(x)

It will prints out 1 2 4, and 3 is missing.

To solve this, you can see this post.

TsReaper
  • 845
  • 7
  • 19