Program to check all tasks can be executed using given server cores or not in Python

PythonServer Side ProgrammingProgramming

Suppose we have two lists, they are cores and tasks. The cores[i] indicates number of cores available in the ith server. And tasks[i] indicates the number of cores needed to execute that task. Each task must be run in only one server. And a server may have multiple tasks to run. We have to check whether it's possible to run all the tasks with the given cores or not.

So, if the input is like cores = [10, 7] tasks = [7, 3, 2, 2, 1], then the output will be True, because we can put tasks[0] and tasks[1] into first server with core 10, and remaining tasks on second server with cores 7.

To solve this, we will follow these steps −

  • Define a function solve() . This will take cores, tasks
  • if tasks set is empty, then
    • return True
  • for i in range 0 to size of cores - 1, do
    • if cores[i] >= tasks[0], then
      • cores[i] := cores[i] - tasks[0]
    • if solve(cores, tasks list except the first task) is true, then
      • return True
    • cores[i] := cores[i] + tasks[0]
  • return False


Let us see the following implementation to get better understanding −

def solve(cores, tasks):
   if not tasks:
      return True

   for i in range(len(cores)):
      if cores[i] >= tasks[0]:
         cores[i] -= tasks[0]
         if solve(cores, tasks[1:]):
            return True
         cores[i] += tasks[0]
   return False

cores = [10, 7]
tasks = [7, 3, 2, 2, 1]
print(solve(cores, tasks))


[10, 7], [7, 3, 2, 2, 1]


Published on 16-Oct-2021 10:36:18