Sure! Here's the Python equivalent of your C++ getProcessTime function. This Python version uses memoization with the @lru_cache decorator to efficiently store and reuse computed results.
from typing import List
from functools import lru_cache
def getProcessTime(time: List[int]) -> List[int]:
n = len(time)
@lru_cache(maxsize=None)
def f(i: int, dff: int) -> int:
if i == n:
return 0
if dff == 0:
option1 = f(i + 1, 0) - time[i]
option2 = f(i + 1, 1) + time[i]
return max(option1, option2)
else:
option1 = f(i + 1, 1) + time[i]
option2 = f(i + 1, 0) - time[i]
return min(option1, option2)
ans = f(0, 0)
total = sum(time)
return [(total + ans) // 2, (total - ans) // 2]
Explanation:
-
Imports and Function Signature:
List is imported from the typing module for type annotations.
lru_cache from the functools module is used to memoize the recursive function f.
-
Function f:
- Parameters:
i: Current index in the time list.
dff: A flag that can be either 0 or 1.
- Base Case:
- If
i equals the length of time, return 0.
- Memoization Check:
- The
@lru_cache decorator automatically caches results, so repeated calls with the same arguments are efficient.
- Recurrence Relation:
- If
dff == 0, calculate the maximum between two options:
- Continue with
dff = 0 and subtract the current time[i].
- Switch to
dff = 1 and add the current time[i].
- If
dff == 1, calculate the minimum between two options:
- Switch to
dff = 1 and add the current time[i].
- Switch to
dff = 0 and subtract the current time[i].
-
Calculating the Answer:
ans stores the result of the recursive function starting from index 0 with dff = 0.
total is the sum of all elements in the time list.
- The final result is a list of two integers:
(total + ans) // 2
(total - ans) // 2
-
Return Value:
- The function returns a list containing two integers, mirroring the
vector<long> return type from the C++ version.
Example Usage:
# Example input
time = [1, 2, 3, 4]
# Function call
result = getProcessTime(time)
print(result) # Output will depend on the logic implemented
Make sure to adjust the logic if there are specific constraints or behaviors you want to implement differently in Python. This translation maintains the original logic and should behave similarly to your C++ function.