How to Implement Interval Scheduling in Python

In this tutorial, we will learn "How to Implement Interval Scheduling in Python". The main objective is to understand interval scheduling and its implementation. This guide will walk you step by step through the process, making it easier to follow and apply. By the end of this tutorial, you will have a solid understanding of how interval scheduling works in Python for this problem, helping you strengthen your problem-solving abilities and improve your overall coding skills in data structure implementation.

This topic is straightforward and easy to understand. By following the instructions provided, you will be able to complete it with ease. The program will guide you step by step through the process of implementing interval scheduling. So, let’s dive into the coding process and start implementing the solution to gain a deeper understanding of Python.

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. def interval_scheduling(stimes, ftimes):
  2.     index = list(range(len(stimes)))
  3.     index.sort(key=lambda i: ftimes[i])
  4.  
  5.     maximal_set = []
  6.     prev_finish_time = 0
  7.  
  8.     for i in index:
  9.         if stimes[i] >= prev_finish_time:
  10.             maximal_set.append(i)
  11.             prev_finish_time = ftimes[i]
  12.  
  13.     return maximal_set
  14.  
  15.  
  16. # MAIN LOOP
  17. while True:
  18.     print("\n========== Implement Interval Scheduling ==========\n")
  19.  
  20.     # Input number of activities
  21.     try:
  22.         n = int(input('Enter number of activities: '))
  23.         if n <= 0:
  24.             print("Number of activities must be positive.")
  25.             continue
  26.     except ValueError:
  27.         print("Invalid input.")
  28.         continue
  29.  
  30.     # Input start times
  31.     try:
  32.         stimes = list(map(int, input(f'Enter {n} start times: ').split()))
  33.         if len(stimes) != n:
  34.             print("You must enter exactly", n, "start times.")
  35.             continue
  36.     except ValueError:
  37.         print("Invalid start times.")
  38.         continue
  39.  
  40.     # Input finish times
  41.     try:
  42.         ftimes = list(map(int, input(f'Enter {n} finish times: ').split()))
  43.         if len(ftimes) != n:
  44.             print("You must enter exactly", n, "finish times.")
  45.             continue
  46.     except ValueError:
  47.         print("Invalid finish times.")
  48.         continue
  49.  
  50.     # Run algorithm
  51.     ans = interval_scheduling(stimes, ftimes)
  52.  
  53.     print("\nSelected activity indices:", ans)
  54.  
  55.     print("Selected activities:")
  56.     for i in ans:
  57.         print(f"Activity {i}: Start = {stimes[i]}, Finish = {ftimes[i]}")
  58.  
  59.     # Try Again Option
  60.     opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
  61.     if opt == "no":
  62.         print("Exiting program...")
  63.         break
  64.     elif opt != "yes":
  65.         print("Invalid choice. Exiting program...")
  66.         break

This Python program implements the Interval Scheduling algorithm using a greedy approach to select the maximum number of non-overlapping activities. It sorts activities based on their finish times and iteratively chooses activities whose start time is greater than or equal to the finish time of the last selected activity. The program runs interactively, allowing users to input start and finish times for activities, then outputs the indices and details of the selected optimal set. It also includes input validation and a loop for repeated execution or exit.

Output:

There you have it we successfully created How to Implement Interval Scheduling in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials