0

I am trying to write a loop that can take all the different combinations of ON_PEAK, MID_PEAK and OFF_PEAK consumption combinations, which will result in the sum of 114.12 of the below-mentioned equation.

I also want those combinations to be appended to a dictionary.

In the dictionary, the key = (SUM of ON_PEAK, MID_PEAK, OFF_PEAK) and the values to be the list of combinations of On_Peak, MID_PEAK and OFF_PEAK combinations. I am new to python and struggle with loops. I appreciate whoever can provide help.

Please see the example below:

d = {}
on_kwh = range(1, 5001, 1)
mid_kwh = range(1, 5001, 1)
off_kwh = range(1, 5001, 1)


if 0.101*(on_kwh) + 0.065(off_kwh) + 0.14(mid_kwh) = 114.12:
    d[on_kwh+mid_kwh+off_kwh].append[on_kwh,off_kwh,mid_kwh] 
    
print(d)


output (Example:1 Combination)
{1000,[150,150,700]}

*Output is based on this logic: 
0.101(150) + 0.0065(150) + 0.14(700) = 114.12
2
  • 0.101 * (150) + 0.0065 * (150) + 0.14 * (700) = 122.9 ? Commented Aug 7, 2020 at 19:40
  • My apologies. it should be 114.12. I have updated my question. Thank you Commented Aug 7, 2020 at 20:04

1 Answer 1

1

you could try a brute force approach, testing all 5000^3 (125'000'000'000) possible combinations of on_kwh, mid_kwh and off_kwh. a better approach would be to do some pruning and to abort your loops, trying a new combination, as soon as the sum exceeds your target value. e.g.

d = dict()
target = 114.12
for on_kwh in range(1, 5001, 1):
    on = on_kwh * 0.101
    if on > target: # can abort here
        break
    for mid_kwh in range(1, 5001, 1):
        mid = mid_kwh * 0.14
        if on + mid > target: # can abort here
            break
        for off_kwh in range(1, 5001, 1):
            off = off_kwh * 0.065
            if on + mid + off > target: # can abort here
                break
            if on + mid + off == target:
                d.setdefault(on_kwh + mid_kwh + off_kwh, []).append([on_kwh, mid_kwh, off_kwh])

print(d) 

this will "only" test 269'348'957 possible combinations.

a yet better/faster approach - in theory - would be to drop the last loop entirely: to be a solution for on_kwh * 0.101 + mid_kwh * 0.14 + off_kwh * 0.065 = 114.12, off_kwh must be off_kwh = (114.12 - on_kwh * 0.101 - mid_kwh * 0.14) / 0.065 for any given pair of values on_kwh and mid_kwh. if off_kwh is an integer in (1, 5000), you found a solution. that being said, the speed up is significant, but you will run into some numeric issues due to working with floating point numbers: you'd have to define some precision up to which level rounding errors are acceptable...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.