Accumulator battery in Python



Problem Statement

Consider a mobile phone, which is in "eco mode". This mode activates once your battery level reaches 20 percent. In this eco mode, the battery drains two times slower than in normal mode.

This means that, in normal mode, if the time consumed by the battery is 1% per minute, then the time taken in eco mode is 1% per 30 seconds (1/2 minute).

Scenario

Now, when we leave our home, we have 100% of the battery. Then t minutes later we have p percent of battery left. We have to find how many minutes we have until our phone will turn off.

For example, if the input time is t=75 minutes and the percentage p=25%, we need to find the time taken for the battery to drain completely.

Calculation

The time taken for the battery to drain from 100% to 25% is 75, the drain per 1% is -

T for 1% = 75 / 75 = 1 minute

The battery drained per minute is 1%. In addition, when the battery reaches below 20 percent, then the time taken is -

1/2 minute

Therefore, the time taken for the battery to drain from 100 % to 75 % is -

Total time = time from 25% to 20% + below 20%
The time taken between 25% to 20% = 5/1 = 5 min 
The time taken below 20% = 20/(1/2) = 40
Then, the total time taken is 40+5 = 45 mins

Algorithm

The following is the algorithm to solve this problem:

  • Check if the battery is in Eco Mode based on the given percentage. If the percentage p is less than 20, i.e, p<20, then returns 2*p*t/(120-2*p).
  • Check if the battery is in Normal Mode. if the percentage p is greater than 20 i.e p>20, then return (p+20) *t/(100-p).

Example: Battery in Eco Mode

In the following, we have calculated the time taken to drain the battery until it becomes zero -

def solve(t, p):
    if p < 20:
        return 2 * p * t / (120 - 2 * p)
    return (p + 20) * t / (100 - p)

print(solve(75, 25))

Following is the output of the above program:

45.0

Example: Battery without Eco Mode

In the following, we have calculated the time taken to drain the battery until it becomes zero when time is 80 and the percentage is 18:

def time_left(t, p):
   if p >= 20:
      normal_rate = (100 - p) / t
      time_to_20 = (p - 20) / normal_rate
      eco_rate = normal_rate / 2
      time_to_0 = 20 / eco_rate
      return time_to_20 + time_to_0
   else:
      eco_time = (20 - p)
      r = (120 - 2 * p) / t
      eco_rate = r / 2
      return p / eco_rate
print(time_left(80, 18))

Following is the output of the above program:

34.285714285714285
Updated on: 2025-07-22T18:50:00+05:30

304 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements