Weighted Interval Scheduling Python Code

Aladdin Persson · Intermediate ·⚡ Algorithms & Data Structures ·6y ago

Key Takeaways

The video implements the weighted interval scheduling problem in Python using dynamic programming, utilizing tools such as lambda functions, bisection search, and the bisect module to compute the optimal solution.

Full Transcript

in this video we want to implement an algorithm in Python on how to solve the weighted interval scheduling problem so I've written some skeleton code and the the function previous intervals will find the P vector which we saw in the last video find solution is used for backtracking to find the optimal jobs compute opt is to apply the recursive formula which we also saw in the last video the way the interval is to find the optimal for each of the subproblems so this is for a specific subset J and here we will run run this one for each of the four for J equals 1 to up to n and so let me just copy in this so I've written out all the all of the jobs which we saw also in the last video the they are the same and also opt for which will we will store all of the optimal solution to all of the subproblems eventually to including all of the jobs where we have n jobs in this case we have 8 + o to store all of the best I guess best jobs to pick so what we want to do first is that we want to sort it by by finished time and finish time is of second element well let's see we will have I to be a list of all of those tuples and we want to sort I when to sort I by the second element so we can use the key so we use the anomalous function lambda and we have the key for each that is a tuple and we want to sort it by the first I mean the this the second element which is first index now that we have it sorted by finish time we want to find the P the p-vector and i think this is the most tricky to find so maybe it's a good thing that we start with this function what we're going to do is we're going to first define P is an empty list we're going to say start to be the list of all of the starting times which is just ask zero for tasks in AI and then the finish which is tasks of one for tasks in AI and the thing we're going to utilize is that we know that this list is sorted right this might not be sorted but we at least know this is sorted because we sorted before we send it into this function then we want to or I in range of Len of I so we want to go through each of art of the jobs and then what we're going to use to make it and so this will make it I'm Quebec City n so for each we have to find an algorithm to find it in log n time and what we can use here is a variant of binary search I guess bisection search so how this function will work and let's our dysfunctional is that let's say we have a list of Finnish times which are sorted so 10 20 30 for example then we have a starting time of let's say 15 so what we know is that this finish time is greater than this one right which means that they overlap but this one finish time is less than or equal to the starting time so we want to have this one right what the bisection method you does is that it will it will first take as input the list which is sorted and it will take an element and it will find where to insert this element so that this list is still sorted right if we insert 15 into the first index here in between 10 and 20 then this will still be sorted and what we want to know is which of all of these elements so what is the index of these of the element where the finish time is less than the starting time so in this case it's 10 right so we can just use this but then subtract 1 and this will be the index so for example if the starting time would be 25 then we know that well this is greater than 25 means at the overlap 20 is less than or equal to 25 which means that they don't overlap and I mean 10 is also less than 25 but we want the greatest index so we want this one which is index 1 so let's say we do the same but we we have start you start which is 25 we will get the first index okay so we just do this index is bisect dot bisect finish come a start of I and then we subtract 1 to get that index and then we just append it right so if it's if it's if it's the zero element if it's the first one so I mean if there are no element then it will be minus one and that's one thing we will have to keep in mind when we do the the the rest of the functions since Python is zero indexed this will be a little bit different from the the video where we went through the algorithm where everything was 1 indexed so a little bit confusing perhaps then we just return P so here we can print P for example - 1 - 1 0 which is contrasted to what we found in the last video this was 0 0 0 1 but that's just because it's 0 indexed so the next thing is that we want to you we want to implement this function which is to apply the recursive formula and so what we want to do if J the base case if J is minus 1 remember zero index so it will be minus 1 instead of 0 at this time then we just return 0 else what we want to do is that we want to return the max of AI of j2 plus compute up of pfj or the compute opt of J minus one right one thing that I believe I'm missing in the last video but we want to do also is that if we already have this value pre-computer we don't want to compute it again so we can do an else--if statement here if zero is if J is very equal to zero and Jays lesson the length of opt which means that essentially we have that one stored right then we can return that instantly right we don't have to come to do this cursive ly all over again if we already have that value computed so this is just to to reuse the item and the the opt values that we've already computed the for then in the wit interval we want to forge a in range of Leno aye I want to go through each of them and then we want to compute opt of J right so it will start from 0 1 etc and then we want to append this to opt okay so we now can print up I guess and so this will just run this for each of the subproblems and then it will have the opt vector which we saw in the last video as well so we have yeah three three four four and then eight for the last three which is exactly the same so it seems to be correct but I guess we want to return opt here but we want to just return to the last one right because this is the optimal total weight for all of the items let's see what is left so what is left is that we want to also find I mean this is great right we have optimal solution which is great eight but we also want to know which items did we we I mean which jobs who did we take so I guess in this case it's easy we can just see that well I know it's this one and I think this one but even for this small case it's a little bit confusing so we want to make a function that can find those using backtracking and similarly here we can write if J is one if my J is minus one then we just return this is the base case and then otherwise we check if if the wait so this is I have J of to write this you just essentially copy this if this where we took that item J is greater equal to opt of J minus one that means that taking the item is at least as good as not taking it or better right then we add this to our to our list of best jobs to pick and we add that jate one and then we call this function again but we now want to have only the intervals that don't overlap with the one we took or if this is not the case then this means that well we want to find the optimal for this regarding item J so then we just want to run it again on J minus one okay so for example in this one here we want to run find solution on on let's see what is if I want to run down find solution the length of I minus one since remember we have it's zero index we just subtract one and then we will have all of the a best jobs to pick in Oh since we have added those in the backtracking so now we can we can print the maximum weight is optimal solution and we also have the best items to pick I keep saying items I mean jobs the best jobs to to take take are the Oh list and the the only thing here is that since we start from the last one and we move our way backwards the items will be in their reverse order so we can right here just revert the order of the list so in this case the maximum weight is 8 oh wait this is not great mmm approximately 10 hours later found the problem right here when we see here when we find the solution we don't want to actually compute it again yes and that causes a problem not really sure why that would cause a problem though but we want to have opted here like this and this adds the job a little bit confusing because I feel if we're just one computer opt on pfj that would still return up to J I mean up tothe pfj for some reason it doesn't and I'm gonna have to think a little bit about about that white actually doesn't either way this should be upped of P of J right because we already have the values computed and so we don't want to run it again and yeah so this is the weighted interval scheduling problem hopefully I'll figure out a solution for why that works and the other one didn't and I mean if you have a an answer for that please comment in the below okay so thanks for watching this video and I hope to see in the in the next one

Original Description

Implementation in Python of the weighted interval scheduling problem in Python using dynamic programming. I try to keep the code as clean as possible and hopefully it's crystal clear for you guys! Code repository: https://github.com/AladdinPerzon/Algorithms-Collection-Python Explanation of algorithm: https://youtu.be/iIX1YvbLbvc
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Aladdin Persson · Aladdin Persson · 23 of 60

1 computeCost.m Linear Regression Cost Function - Machine Learning
computeCost.m Linear Regression Cost Function - Machine Learning
Aladdin Persson
2 gradientDescent.m Gradient Descent Implementation -  Machine Learning
gradientDescent.m Gradient Descent Implementation - Machine Learning
Aladdin Persson
3 Neural Network from scratch - Part 1 (Standard Notation)
Neural Network from scratch - Part 1 (Standard Notation)
Aladdin Persson
4 Neural Network from scratch - Part 2 (Forward Propagation)
Neural Network from scratch - Part 2 (Forward Propagation)
Aladdin Persson
5 Neural Network from scratch - Part 3 (Backward Propagation)
Neural Network from scratch - Part 3 (Backward Propagation)
Aladdin Persson
6 Neural Network from scratch - Part 4 (With Python)
Neural Network from scratch - Part 4 (With Python)
Aladdin Persson
7 sigmoid.m - Programming Assignment 2 Machine Learning
sigmoid.m - Programming Assignment 2 Machine Learning
Aladdin Persson
8 costFunction.m - Programming Assignment 2 Machine Learning
costFunction.m - Programming Assignment 2 Machine Learning
Aladdin Persson
9 predict.m - Programming Assignment 2 Machine Learning
predict.m - Programming Assignment 2 Machine Learning
Aladdin Persson
10 costFunctionReg.m - Programming Assignment 2 Machine Learning
costFunctionReg.m - Programming Assignment 2 Machine Learning
Aladdin Persson
11 lrCostFunction.m - Programming Assignment 3 Machine Learning
lrCostFunction.m - Programming Assignment 3 Machine Learning
Aladdin Persson
12 oneVsAll.m - Programming Assignment 3 Machine Learning
oneVsAll.m - Programming Assignment 3 Machine Learning
Aladdin Persson
13 predictOneVsAll.m - Programming Assignment 3 Machine Learning
predictOneVsAll.m - Programming Assignment 3 Machine Learning
Aladdin Persson
14 predict.m - Programming Assignment 3 Machine Learning
predict.m - Programming Assignment 3 Machine Learning
Aladdin Persson
15 Caesar Cipher Encryption and Decryption with example
Caesar Cipher Encryption and Decryption with example
Aladdin Persson
16 Cryptography: Caesar Cipher Python
Cryptography: Caesar Cipher Python
Aladdin Persson
17 Vigenere Cipher Explained (with Example)
Vigenere Cipher Explained (with Example)
Aladdin Persson
18 Cryptography: Vigenere Cipher Python
Cryptography: Vigenere Cipher Python
Aladdin Persson
19 Hill Cipher Explained (with Example)
Hill Cipher Explained (with Example)
Aladdin Persson
20 Cryptography: Hill Cipher Python
Cryptography: Hill Cipher Python
Aladdin Persson
21 Interval Scheduling Greedy Algorithm: Python
Interval Scheduling Greedy Algorithm: Python
Aladdin Persson
22 Weighted Interval Scheduling Algorithm Explained
Weighted Interval Scheduling Algorithm Explained
Aladdin Persson
Weighted Interval Scheduling Python Code
Weighted Interval Scheduling Python Code
Aladdin Persson
24 Sequence Alignment | Needleman Wunsch Algorithm
Sequence Alignment | Needleman Wunsch Algorithm
Aladdin Persson
25 Sequence Alignment | Needleman Wunsch in Python
Sequence Alignment | Needleman Wunsch in Python
Aladdin Persson
26 Codility BinaryGap Python
Codility BinaryGap Python
Aladdin Persson
27 Codility CyclicRotation Python
Codility CyclicRotation Python
Aladdin Persson
28 Derivation Linear Regression with Gradient Descent
Derivation Linear Regression with Gradient Descent
Aladdin Persson
29 Linear Regression Gradient Descent From Scratch in Python
Linear Regression Gradient Descent From Scratch in Python
Aladdin Persson
30 Pytorch Neural Network example
Pytorch Neural Network example
Aladdin Persson
31 Pytorch CNN example (Convolutional Neural Network)
Pytorch CNN example (Convolutional Neural Network)
Aladdin Persson
32 Pytorch LeNet implementation from scratch
Pytorch LeNet implementation from scratch
Aladdin Persson
33 Pytorch VGG implementation from scratch
Pytorch VGG implementation from scratch
Aladdin Persson
34 Pytorch GoogLeNet / InceptionNet implementation from scratch
Pytorch GoogLeNet / InceptionNet implementation from scratch
Aladdin Persson
35 How to save and load models in Pytorch
How to save and load models in Pytorch
Aladdin Persson
36 How to build custom Datasets for Images in Pytorch
How to build custom Datasets for Images in Pytorch
Aladdin Persson
37 Pytorch Transfer Learning and Fine Tuning Tutorial
Pytorch Transfer Learning and Fine Tuning Tutorial
Aladdin Persson
38 Pytorch Data Augmentation using Torchvision
Pytorch Data Augmentation using Torchvision
Aladdin Persson
39 Pytorch Quick Tip: Weight Initialization
Pytorch Quick Tip: Weight Initialization
Aladdin Persson
40 Pytorch Quick Tip: Using a Learning Rate Scheduler
Pytorch Quick Tip: Using a Learning Rate Scheduler
Aladdin Persson
41 Pytorch ResNet implementation from Scratch
Pytorch ResNet implementation from Scratch
Aladdin Persson
42 Pytorch TensorBoard Tutorial
Pytorch TensorBoard Tutorial
Aladdin Persson
43 Pytorch DCGAN Tutorial (See description for updated video)
Pytorch DCGAN Tutorial (See description for updated video)
Aladdin Persson
44 Naive Bayes from Scratch - Machine Learning Python
Naive Bayes from Scratch - Machine Learning Python
Aladdin Persson
45 Spam Classifier using Naive Bayes in Python
Spam Classifier using Naive Bayes in Python
Aladdin Persson
46 K-Nearest Neighbor from scratch - Machine Learning Python
K-Nearest Neighbor from scratch - Machine Learning Python
Aladdin Persson
47 Linear Regression Normal Equation Python
Linear Regression Normal Equation Python
Aladdin Persson
48 SVM from Scratch - Machine Learning Python (Support Vector Machine)
SVM from Scratch - Machine Learning Python (Support Vector Machine)
Aladdin Persson
49 Neural Network from Scratch - Machine Learning Python
Neural Network from Scratch - Machine Learning Python
Aladdin Persson
50 Pytorch RNN example (Recurrent Neural Network)
Pytorch RNN example (Recurrent Neural Network)
Aladdin Persson
51 Pytorch Bidirectional LSTM example
Pytorch Bidirectional LSTM example
Aladdin Persson
52 Pytorch Text Generator with character level LSTM
Pytorch Text Generator with character level LSTM
Aladdin Persson
53 Logistic Regression from Scratch - Machine Learning Python
Logistic Regression from Scratch - Machine Learning Python
Aladdin Persson
54 K-Means Clustering from Scratch - Machine Learning Python
K-Means Clustering from Scratch - Machine Learning Python
Aladdin Persson
55 Pytorch Torchtext Tutorial 1: Custom Datasets and loading JSON/CSV/TSV files
Pytorch Torchtext Tutorial 1: Custom Datasets and loading JSON/CSV/TSV files
Aladdin Persson
56 Pytorch Torchtext Tutorial 2: Built in Datasets with Example
Pytorch Torchtext Tutorial 2: Built in Datasets with Example
Aladdin Persson
57 Pytorch Torchtext Tutorial 3: From Textfiles to Dataset
Pytorch Torchtext Tutorial 3: From Textfiles to Dataset
Aladdin Persson
58 Paper Review: Sequence to Sequence Learning with Neural Networks
Paper Review: Sequence to Sequence Learning with Neural Networks
Aladdin Persson
59 Pytorch Seq2Seq Tutorial for Machine Translation
Pytorch Seq2Seq Tutorial for Machine Translation
Aladdin Persson
60 Pytorch Seq2Seq with Attention for Machine Translation
Pytorch Seq2Seq with Attention for Machine Translation
Aladdin Persson

The video teaches how to implement the weighted interval scheduling problem in Python using dynamic programming, covering topics such as job selection, optimization, and backtracking. It provides a clear and concise explanation of the algorithm and its implementation.

Key Takeaways
  1. Sort jobs by finish time using a lambda function
  2. Find the P-vector by iterating over sorted jobs
  3. Implement the recursive formula to compute the optimal solution
  4. Use backtracking to find the best jobs to pick
  5. Compute the maximum weight of the optimal solution
  6. Run find_solution on the length of I minus one
  7. Revert the order of the list of selected jobs
💡 The weighted interval scheduling problem can be solved efficiently using dynamic programming and backtracking, allowing for optimal job selection and maximum weight computation.

Related AI Lessons

Bloom Filters, Explained Properly
Learn how Bloom filters work and their benefits, including tiny memory and blazing speed, in exchange for potential false positives.
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Learn how prefix sums enable instant range queries in arrays, boosting performance in various applications
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
A simple math question can destroy a developer's interview, highlighting the importance of being prepared for unexpected questions
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Learn to remove duplicates from a sorted array using the two pointers technique, improving from brute force to optimized solutions
Medium · Python
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →