Optimizing Job Assignments with Python: A Greedy Approach

Job Assignment

In this article, we will learn the skill of job assignment which is a very important topic in the field of Operations Research. For this, we will utilize Python programming language and the Numpy library for the same. We will also solve a small case on a job assignment.

Job assignment involves allocating tasks to workers while minimizing overall completion time or cost. Python’s greedy algorithm, combined with NumPy, can solve such problems by iteratively assigning jobs based on worker skills and constraints, enabling efficient resource management in various industries.

Recommended: Maximizing Cost Savings Through Offshore Development: A Comprehensive Guide

Recommended: Delivery Route Optimization using Python: A Step-by-Step Guide

What is a Job Assignment?

Let us understand what a job assignment is with an example. In our example, three tasks have to be completed. Three workers have different sets of skills and take different amounts of time to complete the above-mentioned tasks. Now our goal is to assign the jobs to the workers to minimize the period of completing the three tasks.

Now, we solve the above problem using the concepts of Linear programming. Now there are certain constraints as well, each worker can be assigned only a single job at a time. Our objective function is the sum of all the time taken by the workers and minimize it. Let us now solve this problem using the power of the Numpy library of Python programming language.

Let us now look at the output of the problem.

Job Assignment Output

From the output, we can see that The assignment is complete and optimized. Let us now look at a small case and understand the job assignment further.

A Real-World Job Assignment Scenario

Continuing with the example of assigning workers some jobs, in this case, a company is looking to get some work done with the help of some freelancers. There are 15 jobs and we have 10 freelancers. We have to assign jobs to workers in such a way, that we minimize the time as well as the cost of the whole operation. Let us now model this in the Python programming language.

This problem is solved using the greedy algorithm. In short, the greedy algorithm selects the most optimal choice available and does not consider what will happen in the future while making this choice. In the above code, we have randomly generated data on freelancer details. Let us now look at the output of the code.

Job Assignment Case Study

Thus, we complete our agenda of job assignment while minimizing costs as evidenced by the output.

Assigning jobs optimally is crucial for maximizing productivity and minimizing costs in today’s competitive landscape. Python’s powerful libraries like NumPy make it easy to implement greedy algorithms and solve complex job assignment problems, even with larger sets of jobs and workers. How could you adapt this approach to accommodate dynamic changes in job requirements or worker availability?

Recommended: Splitting Lists into Sub-Lists in Python: Techniques and Advantages

Recommended: Object Detection with OpenCV: A Step-by-Step Tutorial

Logo

Say "Hello, World!" With Python Easy Max Score: 5 Success Rate: 96.22%

Python if-else easy python (basic) max score: 10 success rate: 89.67%, arithmetic operators easy python (basic) max score: 10 success rate: 97.39%, python: division easy python (basic) max score: 10 success rate: 98.68%, loops easy python (basic) max score: 10 success rate: 98.09%, write a function medium python (basic) max score: 10 success rate: 90.30%, print function easy python (basic) max score: 20 success rate: 97.28%, list comprehensions easy python (basic) max score: 10 success rate: 97.68%, find the runner-up score easy python (basic) max score: 10 success rate: 94.18%, nested lists easy python (basic) max score: 10 success rate: 91.73%, cookie support is required to access hackerrank.

Seems like cookies are disabled on this browser, please enable them to open this website

Google OR-Tools

  • Google OR-Tools
  • Español – América Latina
  • Português – Brasil
  • Tiếng Việt

Solving an Assignment Problem

This section presents an example that shows how to solve an assignment problem using both the MIP solver and the CP-SAT solver.

In the example there are five workers (numbered 0-4) and four tasks (numbered 0-3). Note that there is one more worker than in the example in the Overview .

The costs of assigning workers to tasks are shown in the following table.

Worker Task 0 Task 1 Task 2 Task 3
90 80 75 70
35 85 55 65
125 95 90 95
45 110 95 115
50 100 90 100

The problem is to assign each worker to at most one task, with no two workers performing the same task, while minimizing the total cost. Since there are more workers than tasks, one worker will not be assigned a task.

MIP solution

The following sections describe how to solve the problem using the MPSolver wrapper .

Import the libraries

The following code imports the required libraries.

Create the data

The following code creates the data for the problem.

The costs array corresponds to the table of costs for assigning workers to tasks, shown above.

Declare the MIP solver

The following code declares the MIP solver.

Create the variables

The following code creates binary integer variables for the problem.

Create the constraints

Create the objective function.

The following code creates the objective function for the problem.

The value of the objective function is the total cost over all variables that are assigned the value 1 by the solver.

Invoke the solver

The following code invokes the solver.

Print the solution

The following code prints the solution to the problem.

Here is the output of the program.

Complete programs

Here are the complete programs for the MIP solution.

CP SAT solution

The following sections describe how to solve the problem using the CP-SAT solver.

Declare the model

The following code declares the CP-SAT model.

The following code sets up the data for the problem.

The following code creates the constraints for the problem.

Here are the complete programs for the CP-SAT solution.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License , and code samples are licensed under the Apache 2.0 License . For details, see the Google Developers Site Policies . Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2023-01-02 UTC.

Python Coding Assignments on CodeSubmit

Looking for a better way to hire Python developers? CodeSubmit is the best coding challenge platform for assessing Python devs! Our carefully curated library of Python coding assessments helps you to identify top candidates. Uncover candidate competencies and hire your next Python developer with confidence.

Python Coding Assignments on CodeSubmit

Identify Top Python Candidates

Evaluate for on-the-job skills.

Evaluate Python developers with Python-specific coding assessments. We support the most popular Python frameworks so that you can be confident that your next hire is proficient in your stack . Choose from our library of Python coding challenges or upload your own. We also have Python assignments specifically for data engineers ! Quickly and accurately identify qualified candidates and hire the right Python developer for your team.

Better hiring decisions

Since you're qualifying candidates based on their real Python language (and framework) skills, you can rest easy knowing you're making an informed hiring decision. Our assignments are challenging but fun, so your future candidates will appreciate your great hiring process. And for your follow-up interviews , we've collected a list of great Python interview questions !

How it works

Create an account with CodeSubmit, select one of our excellent Python coding assessments, or upload your own, and get started inviting candidates. Our suite of review features makes identifying top performers simple. Reduce hiring time, and snag the best Python developer for your growing team.

Pyramid

No braindead code challenges just real-world tasks for real-world engineers. That's why we at Finn love CodeSubmit.

Andreas Stryz

Real tasks, not brainteasers.

Take-home Challenges

Our library of real-world tasks gives you an accurate measure of every candidate’s coding skills, whilst providing them with a fair and considerate interview experience.

Pyramid

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

assignment-problem

Here are 24 public repositories matching this topic..., root-11 / graph-theory.

A simple graph library

  • Updated Apr 29, 2024

mayorx / hungarian-algorithm

(Kuhn-Munkres) numpy implementation, rectangular matrix is supported (|X| <= |Y|). 100x100000 in 0.153 s.

  • Updated Dec 8, 2022

sharathadavanne / hungarian-net

Deep-learning-based implementation of the popular Hungarian algorithm that helps solve the assignment problem.

  • Updated Aug 31, 2023

YaleDHLab / pointgrid

Transform a 2D point distribution to a hex grid to avoid overplotting in data visualizations

  • Updated Jun 30, 2021

dutta-alankar / PH-354-2019-IISc-Assignment-Problems

Solutions to the complete set of assignment problems which I did while crediting Computational Physics course by Prof. Manish Jain at IISc, Physical Sciences department on 2019

  • Updated May 30, 2021

Ibrahim5aad / kuhn-munkres-algorithm

A python program to solve assignment problem by the Kuhn–Munkres algorithm (The Hungarian Method).

  • Updated Oct 22, 2021

alierenekinci / SoforAtama

Driver Assignment WebUi

  • Updated Jan 14, 2024

kachark / FormFlight

Simulation framework for autonomous vehicle formation and assignment

  • Updated Oct 30, 2021

dilsonpereira / BipartiteMatching

Python implementation of algorithms for maximum cardinality matching and maximum cost assignment in bipartite graphs

  • Updated Jul 25, 2019

swetanksaha / cse4589-pa3

AutoGrader & Student Template for the CSE 4/589: Programming Assignment 3 (PA3) [For use by TA & Course Instructors]

  • Updated Jan 21, 2018

torressa / glovo

Some work I did for an interview for a job as a data scientist optimisation specialist

  • Updated Jul 22, 2020

swetanksaha / cse4589-pa1

AutoGrader & Student Template for the CSE 4/589: Programming Assignment 1 (PA1) [For use by TA & Course Instructors]

  • Updated Jan 23, 2019

asujaykk / MultiObjectTracker

An object tracker for realtime multiple objects tracking

  • Updated Jan 9, 2023

zhiao777774 / task-assignment-tool

  • Updated Nov 21, 2022

castroisabel / assignment-problem

Two different solutions for the assignment problem using the GLPK solver and the greedy algorithm.

  • Updated Jan 1, 2022

calcoloergosum / assignment-enumeration-python

  • Updated Jun 7, 2021

dde-labs / kkps-el-http

KKPS Assignment that Extract & Load data from the FMP

  • Updated Jun 23, 2024

Iwilsonp / stable-scioly-team-assigner

  • Updated Jan 30, 2018

simranjeet97 / RecyclingMachine

Python Recycling Machine Based on OOPS Concepts.

  • Updated Feb 8, 2019

mridulgain / spyder

Simple Python Debugger

  • Updated Jan 26, 2020

Improve this page

Add a description, image, and links to the assignment-problem topic page so that developers can more easily learn about it.

Curate this topic

Add this topic to your repo

To associate your repository with the assignment-problem topic, visit your repo's landing page and select "manage topics."

Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python assignment operators.

Assignment operators are used to assign values to variables:

Operator Example Same As Try it
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

Related Pages

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Python Programming

Practice Python Exercises and Challenges with Solutions

Free Coding Exercises for Python Developers. Exercises cover Python Basics , Data structure , to Data analytics . As of now, this page contains 18 Exercises.

What included in these Python Exercises?

Each exercise contains specific Python topic questions you need to practice and solve. These free exercises are nothing but Python assignments for the practice where you need to solve different programs and challenges.

  • All exercises are tested on Python 3.
  • Each exercise has 10-20 Questions.
  • The solution is provided for every question.
  • Practice each Exercise in Online Code Editor

These Python programming exercises are suitable for all Python developers. If you are a beginner, you will have a better understanding of Python after solving these exercises. Below is the list of exercises.

Select the exercise you want to solve .

Basic Exercise for Beginners

Practice and Quickly learn Python’s necessary skills by solving simple questions and problems.

Topics : Variables, Operators, Loops, String, Numbers, List

Python Input and Output Exercise

Solve input and output operations in Python. Also, we practice file handling.

Topics : print() and input() , File I/O

Python Loop Exercise

This Python loop exercise aims to help developers to practice branching and Looping techniques in Python.

Topics : If-else statements, loop, and while loop.

Python Functions Exercise

Practice how to create a function, nested functions, and use the function arguments effectively in Python by solving different questions.

Topics : Functions arguments, built-in functions.

Python String Exercise

Solve Python String exercise to learn and practice String operations and manipulations.

Python Data Structure Exercise

Practice widely used Python types such as List, Set, Dictionary, and Tuple operations in Python

Python List Exercise

This Python list exercise aims to help Python developers to learn and practice list operations.

Python Dictionary Exercise

This Python dictionary exercise aims to help Python developers to learn and practice dictionary operations.

Python Set Exercise

This exercise aims to help Python developers to learn and practice set operations.

Python Tuple Exercise

This exercise aims to help Python developers to learn and practice tuple operations.

Python Date and Time Exercise

This exercise aims to help Python developers to learn and practice DateTime and timestamp questions and problems.

Topics : Date, time, DateTime, Calendar.

Python OOP Exercise

This Python Object-oriented programming (OOP) exercise aims to help Python developers to learn and practice OOP concepts.

Topics : Object, Classes, Inheritance

Python JSON Exercise

Practice and Learn JSON creation, manipulation, Encoding, Decoding, and parsing using Python

Python NumPy Exercise

Practice NumPy questions such as Array manipulations, numeric ranges, Slicing, indexing, Searching, Sorting, and splitting, and more.

Python Pandas Exercise

Practice Data Analysis using Python Pandas. Practice Data-frame, Data selection, group-by, Series, sorting, searching, and statistics.

Python Matplotlib Exercise

Practice Data visualization using Python Matplotlib. Line plot, Style properties, multi-line plot, scatter plot, bar chart, histogram, Pie chart, Subplot, stack plot.

Random Data Generation Exercise

Practice and Learn the various techniques to generate random data in Python.

Topics : random module, secrets module, UUID module

Python Database Exercise

Practice Python database programming skills by solving the questions step by step.

Use any of the MySQL, PostgreSQL, SQLite to solve the exercise

Exercises for Intermediate developers

The following practice questions are for intermediate Python developers.

If you have not solved the above exercises, please complete them to understand and practice each topic in detail. After that, you can solve the below questions quickly.

Exercise 1: Reverse each word of a string

Expected Output

  • Use the split() method to split a string into a list of words.
  • Reverse each word from a list
  • finally, use the join() function to convert a list into a string

Steps to solve this question :

  • Split the given string into a list of words using the split() method
  • Use a list comprehension to create a new list by reversing each word from a list.
  • Use the join() function to convert the new list into a string
  • Display the resultant string

Exercise 2: Read text file into a variable and replace all newlines with space

Given : Assume you have a following text file (sample.txt).

Expected Output :

  • First, read a text file.
  • Next, use string replace() function to replace all newlines ( \n ) with space ( ' ' ).

Steps to solve this question : -

  • First, open the file in a read mode
  • Next, read all content from a file using the read() function and assign it to a variable.
  • Display final string

Exercise 3: Remove items from a list while iterating

Description :

In this question, You need to remove items from a list while iterating but without creating a different copy of a list.

Remove numbers greater than 50

Expected Output : -

  • Get the list's size
  • Iterate list using while loop
  • Check if the number is greater than 50
  • If yes, delete the item using a del keyword
  • Reduce the list size

Solution 1: Using while loop

Solution 2: Using for loop and range()

Exercise 4: Reverse Dictionary mapping

Exercise 5: display all duplicate items from a list.

  • Use the counter() method of the collection module.
  • Create a dictionary that will maintain the count of each item of a list. Next, Fetch all keys whose value is greater than 2

Solution 1 : - Using collections.Counter()

Solution 2 : -

Exercise 6: Filter dictionary to contain keys present in the given list

Exercise 7: print the following number pattern.

Refer to Print patterns in Python to solve this question.

  • Use two for loops
  • The outer loop is reverse for loop from 5 to 0
  • Increment value of x by 1 in each iteration of an outer loop
  • The inner loop will iterate from 0 to the value of i of the outer loop
  • Print value of x in each iteration of an inner loop
  • Print newline at the end of each outer loop

Exercise 8: Create an inner function

Question description : -

  • Create an outer function that will accept two strings, x and y . ( x= 'Emma' and y = 'Kelly' .
  • Create an inner function inside an outer function that will concatenate x and y.
  • At last, an outer function will join the word 'developer' to it.

Exercise 9: Modify the element of a nested list inside the following list

Change the element 35 to 3500

Exercise 10: Access the nested key increment from the following dictionary

Under Exercises: -

Python Object-Oriented Programming (OOP) Exercise: Classes and Objects Exercises

Updated on:  December 8, 2021 | 51 Comments

Python Date and Time Exercise with Solutions

Updated on:  December 8, 2021 | 11 Comments

Python Dictionary Exercise with Solutions

Updated on:  May 6, 2023 | 57 Comments

Python Tuple Exercise with Solutions

Updated on:  December 8, 2021 | 95 Comments

Python Set Exercise with Solutions

Updated on:  October 20, 2022 | 27 Comments

Python if else, for loop, and range() Exercises with Solutions

Updated on:  September 6, 2021 | 294 Comments

Updated on:  August 2, 2022 | 153 Comments

Updated on:  September 6, 2021 | 108 Comments

Python List Exercise with Solutions

Updated on:  December 8, 2021 | 197 Comments

Updated on:  December 8, 2021 | 7 Comments

Python Data Structure Exercise for Beginners

Updated on:  December 8, 2021 | 116 Comments

Python String Exercise with Solutions

Updated on:  October 6, 2021 | 221 Comments

Updated on:  March 9, 2021 | 23 Comments

Updated on:  March 9, 2021 | 51 Comments

Updated on:  July 20, 2021 | 29 Comments

Python Basic Exercise for Beginners

Updated on:  August 31, 2023 | 492 Comments

Useful Python Tips and Tricks Every Programmer Should Know

Updated on:  May 17, 2021 | 23 Comments

Python random Data generation Exercise

Updated on:  December 8, 2021 | 13 Comments

Python Database Programming Exercise

Updated on:  March 9, 2021 | 17 Comments

  • Online Python Code Editor

Updated on:  June 1, 2022 |

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills .

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Python Tricks

To get New Python Tutorials, Exercises, and Quizzes

Legal Stuff

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use , Cookie Policy , and Privacy Policy .

Copyright © 2018–2024 pynative.com

  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

Different Forms of Assignment Statements in Python

We use Python assignment statements to assign objects to names. The target of an assignment statement is written on the left side of the equal sign (=), and the object on the right can be an arbitrary expression that computes an object.

There are some important properties of assignment in Python :-

  • Assignment creates object references instead of copying the objects.
  • Python creates a variable name the first time when they are assigned a value.
  • Names must be assigned before being referenced.
  • There are some operations that perform assignments implicitly.

Assignment statement forms :-

1. Basic form:

This form is the most common form.

2. Tuple assignment:

    

When we code a tuple on the left side of the =, Python pairs objects on the right side with targets on the left by position and assigns them from left to right. Therefore, the values of x and y are 50 and 100 respectively.

3. List assignment:

This works in the same way as the tuple assignment.

 

4. Sequence assignment:

In recent version of Python, tuple and list assignment have been generalized into instances of what we now call sequence assignment – any sequence of names can be assigned to any sequence of values, and Python assigns the items one at a time by position.

 

5. Extended Sequence unpacking:

It allows us to be more flexible in how we select portions of a sequence to assign.

Here, p is matched with the first character in the string on the right and q with the rest. The starred name (*q) is assigned a list, which collects all items in the sequence not assigned to other names.

This is especially handy for a common coding pattern such as splitting a sequence and accessing its front and rest part.

 

6. Multiple- target assignment:

 

In this form, Python assigns a reference to the same object (the object which is rightmost) to all the target on the left.

7. Augmented assignment :

The augmented assignment is a shorthand assignment that combines an expression and an assignment.

      

There are several other augmented assignment forms:

Please Login to comment...

Similar reads.

  • python-basics
  • Python Programs

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Python Tutorial

  • Python Basics
  • Python - Home
  • Python - Overview
  • Python - History
  • Python - Features
  • Python vs C++
  • Python - Hello World Program
  • Python - Application Areas
  • Python - Interpreter
  • Python - Environment Setup
  • Python - Virtual Environment
  • Python - Basic Syntax
  • Python - Variables
  • Python - Data Types
  • Python - Type Casting
  • Python - Unicode System
  • Python - Literals
  • Python - Operators
  • Python - Arithmetic Operators
  • Python - Comparison Operators

Python - Assignment Operators

  • Python - Logical Operators
  • Python - Bitwise Operators
  • Python - Membership Operators
  • Python - Identity Operators
  • Python - Operator Precedence
  • Python - Comments
  • Python - User Input
  • Python - Numbers
  • Python - Booleans
  • Python Control Statements
  • Python - Control Flow
  • Python - Decision Making
  • Python - If Statement
  • Python - If else
  • Python - Nested If
  • Python - Match-Case Statement
  • Python - Loops
  • Python - for Loops
  • Python - for-else Loops
  • Python - While Loops
  • Python - break Statement
  • Python - continue Statement
  • Python - pass Statement
  • Python - Nested Loops
  • Python Functions & Modules
  • Python - Functions
  • Python - Default Arguments
  • Python - Keyword Arguments
  • Python - Keyword-Only Arguments
  • Python - Positional Arguments
  • Python - Positional-Only Arguments
  • Python - Arbitrary Arguments
  • Python - Variables Scope
  • Python - Function Annotations
  • Python - Modules
  • Python - Built in Functions
  • Python Strings
  • Python - Strings
  • Python - Slicing Strings
  • Python - Modify Strings
  • Python - String Concatenation
  • Python - String Formatting
  • Python - Escape Characters
  • Python - String Methods
  • Python - String Exercises
  • Python Lists
  • Python - Lists
  • Python - Access List Items
  • Python - Change List Items
  • Python - Add List Items
  • Python - Remove List Items
  • Python - Loop Lists
  • Python - List Comprehension
  • Python - Sort Lists
  • Python - Copy Lists
  • Python - Join Lists
  • Python - List Methods
  • Python - List Exercises
  • Python Tuples
  • Python - Tuples
  • Python - Access Tuple Items
  • Python - Update Tuples
  • Python - Unpack Tuples
  • Python - Loop Tuples
  • Python - Join Tuples
  • Python - Tuple Methods
  • Python - Tuple Exercises
  • Python Sets
  • Python - Sets
  • Python - Access Set Items
  • Python - Add Set Items
  • Python - Remove Set Items
  • Python - Loop Sets
  • Python - Join Sets
  • Python - Copy Sets
  • Python - Set Operators
  • Python - Set Methods
  • Python - Set Exercises
  • Python Dictionaries
  • Python - Dictionaries
  • Python - Access Dictionary Items
  • Python - Change Dictionary Items
  • Python - Add Dictionary Items
  • Python - Remove Dictionary Items
  • Python - Dictionary View Objects
  • Python - Loop Dictionaries
  • Python - Copy Dictionaries
  • Python - Nested Dictionaries
  • Python - Dictionary Methods
  • Python - Dictionary Exercises
  • Python Arrays
  • Python - Arrays
  • Python - Access Array Items
  • Python - Add Array Items
  • Python - Remove Array Items
  • Python - Loop Arrays
  • Python - Copy Arrays
  • Python - Reverse Arrays
  • Python - Sort Arrays
  • Python - Join Arrays
  • Python - Array Methods
  • Python - Array Exercises
  • Python File Handling
  • Python - File Handling
  • Python - Write to File
  • Python - Read Files
  • Python - Renaming and Deleting Files
  • Python - Directories
  • Python - File Methods
  • Python - OS File/Directory Methods
  • Python - OS Path Methods
  • Object Oriented Programming
  • Python - OOPs Concepts
  • Python - Classes & Objects
  • Python - Class Attributes
  • Python - Class Methods
  • Python - Static Methods
  • Python - Constructors
  • Python - Access Modifiers
  • Python - Inheritance
  • Python - Polymorphism
  • Python - Method Overriding
  • Python - Method Overloading
  • Python - Dynamic Binding
  • Python - Dynamic Typing
  • Python - Abstraction
  • Python - Encapsulation
  • Python - Interfaces
  • Python - Packages
  • Python - Inner Classes
  • Python - Anonymous Class and Objects
  • Python - Singleton Class
  • Python - Wrapper Classes
  • Python - Enums
  • Python - Reflection
  • Python Errors & Exceptions
  • Python - Syntax Errors
  • Python - Exceptions
  • Python - try-except Block
  • Python - try-finally Block
  • Python - Raising Exceptions
  • Python - Exception Chaining
  • Python - Nested try Block
  • Python - User-defined Exception
  • Python - Logging
  • Python - Assertions
  • Python - Built-in Exceptions
  • Python Multithreading
  • Python - Multithreading
  • Python - Thread Life Cycle
  • Python - Creating a Thread
  • Python - Starting a Thread
  • Python - Joining Threads
  • Python - Naming Thread
  • Python - Thread Scheduling
  • Python - Thread Pools
  • Python - Main Thread
  • Python - Thread Priority
  • Python - Daemon Threads
  • Python - Synchronizing Threads
  • Python Synchronization
  • Python - Inter-thread Communication
  • Python - Thread Deadlock
  • Python - Interrupting a Thread
  • Python Networking
  • Python - Networking
  • Python - Socket Programming
  • Python - URL Processing
  • Python - Generics
  • Python Libraries
  • NumPy Tutorial
  • Pandas Tutorial
  • SciPy Tutorial
  • Matplotlib Tutorial
  • Django Tutorial
  • OpenCV Tutorial
  • Python Miscellenous
  • Python - Date & Time
  • Python - Maths
  • Python - Iterators
  • Python - Generators
  • Python - Closures
  • Python - Decorators
  • Python - Recursion
  • Python - Reg Expressions
  • Python - PIP
  • Python - Database Access
  • Python - Weak References
  • Python - Serialization
  • Python - Templating
  • Python - Output Formatting
  • Python - Performance Measurement
  • Python - Data Compression
  • Python - CGI Programming
  • Python - XML Processing
  • Python - GUI Programming
  • Python - Command-Line Arguments
  • Python - Docstrings
  • Python - JSON
  • Python - Sending Email
  • Python - Further Extensions
  • Python - Tools/Utilities
  • Python - GUIs
  • Python Useful Resources
  • Python Compiler
  • NumPy Compiler
  • Matplotlib Compiler
  • SciPy Compiler
  • Python - Questions & Answers
  • Python - Online Quiz
  • Python - Programming Examples
  • Python - Quick Guide
  • Python - Useful Resources
  • Python - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Python Assignment Operator

The = (equal to) symbol is defined as assignment operator in Python. The value of Python expression on its right is assigned to a single variable on its left. The = symbol as in programming in general (and Python in particular) should not be confused with its usage in Mathematics, where it states that the expressions on the either side of the symbol are equal.

Example of Assignment Operator in Python

Consider following Python statements −

At the first instance, at least for somebody new to programming but who knows maths, the statement "a=a+b" looks strange. How could a be equal to "a+b"? However, it needs to be reemphasized that the = symbol is an assignment operator here and not used to show the equality of LHS and RHS.

Because it is an assignment, the expression on right evaluates to 15, the value is assigned to a.

In the statement "a+=b", the two operators "+" and "=" can be combined in a "+=" operator. It is called as add and assign operator. In a single statement, it performs addition of two operands "a" and "b", and result is assigned to operand on left, i.e., "a".

Augmented Assignment Operators in Python

In addition to the simple assignment operator, Python provides few more assignment operators for advanced use. They are called cumulative or augmented assignment operators. In this chapter, we shall learn to use augmented assignment operators defined in Python.

Python has the augmented assignment operators for all arithmetic and comparison operators.

Python augmented assignment operators combines addition and assignment in one statement. Since Python supports mixed arithmetic, the two operands may be of different types. However, the type of left operand changes to the operand of on right, if it is wider.

The += operator is an augmented operator. It is also called cumulative addition operator, as it adds "b" in "a" and assigns the result back to a variable.

The following are the augmented assignment operators in Python:

  • Augmented Addition Operator
  • Augmented Subtraction Operator
  • Augmented Multiplication Operator
  • Augmented Division Operator
  • Augmented Modulus Operator
  • Augmented Exponent Operator
  • Augmented Floor division Operator

Augmented Addition Operator (+=)

Following examples will help in understanding how the "+=" operator works −

It will produce the following output −

Augmented Subtraction Operator (-=)

Use -= symbol to perform subtract and assign operations in a single statement. The "a-=b" statement performs "a=a-b" assignment. Operands may be of any number type. Python performs implicit type casting on the object which is narrower in size.

Augmented Multiplication Operator (*=)

The "*=" operator works on similar principle. "a*=b" performs multiply and assign operations, and is equivalent to "a=a*b". In case of augmented multiplication of two complex numbers, the rule of multiplication as discussed in the previous chapter is applicable.

Augmented Division Operator (/=)

The combination symbol "/=" acts as divide and assignment operator, hence "a/=b" is equivalent to "a=a/b". The division operation of int or float operands is float. Division of two complex numbers returns a complex number. Given below are examples of augmented division operator.

Augmented Modulus Operator (%=)

To perform modulus and assignment operation in a single statement, use the %= operator. Like the mod operator, its augmented version also is not supported for complex number.

Augmented Exponent Operator (**=)

The "**=" operator results in computation of "a" raised to "b", and assigning the value back to "a". Given below are some examples −

Augmented Floor division Operator (//=)

For performing floor division and assignment in a single statement, use the "//=" operator. "a//=b" is equivalent to "a=a//b". This operator cannot be used with complex numbers.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Algorithm for fairly assigning tasks to workers based on skills

(Before anyone asks, this is not homework.)

I have a set of workers with interests, i.e.:

Bob: Java, XML, Ruby

Susan: Java, HTML, Python

Fred: Python, Ruby

Sam: Java, Ruby

(There are actually somewhere in the range of 10-25 "interests" for each worker, and I have around 40-50 workers)

At the same time, I have a very large set of tasks that need to be distributed among the workers. Each task has to be assigned to at least 3 workers, and the workers must match at least one of the tasks' interests:

Task 1: Ruby, XML Task 2: XHTML, Python

and so on. So Bob, Fred, or Sam could get Task 1; Susan or Fred could get Task 2.

This is all stored in a database thusly:

Each worker has a maximum number of assignments they will do, around 10. Some interests are more rare than others (i.e. only 1 or 2 workers have listed them as a interest), some interests are more common (i.e. half of the workers list them).

The algorithm must :

  • Assign every task to 3 workers (it is assumed that at least 3 of the workers are interested in one of the interests of the task).
  • Assign every worker 1 or more tasks

Ideally, the algorithm will:

  • Assign each worker a number of tasks proportional to their maximum assignments and the total number of tasks. For example, if Susan says she will do 20 tasks and most people will only do 10 tasks and there are 50 workers and 300 tasks, she should be assigned 12 tasks (20/10*(300/50)).
  • Assign a variety of tasks to each worker, so if Susan lists 4 interests she gets tasks that include 4 interests (rather than getting 10 tasks all with the same interest)

The most difficult aspect so far has been dealing with theses issues:

  • tasks having interests with few corresponding workers
  • workers who have few interests, especially
  • workers who have a few interests, for which there are relatively few tasks

Jordan Reiter's user avatar

  • 3 This is a GREAT question, but I'm curious if you could be a bit more specific about what you're trying to optimize. Is there some particular value you want to maximize or minimize? And, if so, could you tell us what it is? Right now this is an interesting question, but I think it's a bit underspecified. –  templatetypedef Commented Jan 21, 2011 at 23:51
  • 1 The goal is honestly a fairer allocation of tasks. Currently there isn't a formal algorithm, more of a brute force "loop through the tasks, from ordering first by tasks with the fewest matching workers, then assign to workers, ordered by how many they already have assigned" This ends up with some workers getting too many or too few assignments. –  Jordan Reiter Commented Jan 25, 2011 at 7:16

4 Answers 4

This problem can be modeled as a Maximum Flow Problem .

In a max-flow problem, you have a directed graph with two special nodes, the source and the sink. The edges in the graph have capacities, and your goal is to assign a flow through the graph from the source to the sink without exceeding any of the edge capacities.

With a (very) carefully crafted graph, we can find an assignment meeting your requirements from the maximum flow.

Let me number the requirements.

I will assume that the maximum flow is found using the Edmonds-Karp Algorithm .

Let's first find a graph that meets requirements 1-3.

Picture the graph as 4 columns of nodes, where edges only go from nodes in a column to nodes in the neighboring column to the right.

In the first column we have the source node. In the next column we will have nodes for each of the workers. From the source, there is an edge to each worker with capacity equal to that worker's maximum assignments. This will enforce requirement 1.

In the third column, there is a node for each task. From each worker in the second column there is an edge to each task that that worker is interested in with a capacity of 1 (a worker is interested in a task if the intersection of their interests is non-empty). This will enforce requirement 2. The capacity of 1 will ensure that each worker takes only 1 of the 3 slots for each task.

In the fourth column we have the sink. There is an edge from each task to the sink with capacity 3. This will enforce requirement 3.

Now, we find a maximum flow in this graph using the Edmonds-Karp Algorithm. If this maximum flow is less than 3 * (# of tasks) then there is no assignment meeting requirements 1-3. If not, there is such an assignment and we can find it by examining the final augmented graph. In the augmented graph, if there is an edge from a task to a worker with capacity 1, then that worker is assigned to that task.

Now, we will modify our graph and algorithm to meet the rest of the requirements.

First, let's meet requirement 4. This will require a small change to the algorithm. Initially, set all the capacities from the source to the workers to 1. Find the max-flow in this graph. If the flow is not equal to the number of workers, then there is no assignment meeting requirement 4. Now, in your final residual graph, for each worker the edge from the source to that worker has capacity 0 and the reverse edge has capacity 1. Change these to that worker's maximum assignments - 1 and 0 , respectively. Now continue Edmonds-Karp algorithm as before. Basically what we have done is first find an assignment such that each worker is assigned to exactly one task. Then delete the reverse edge from that task so that the worker will always be assigned to at least one task(though it may not be the one assigned to in the first pass).

Now let's meet requirement 5. Strictly speaking, this requirement just means that we divide each worker's maximum assignments by sum of all worker's maximum assignments / number of tasks . This will quite possibly not have a satisfying assignment. But that's ok. Initialize our graph with these new maximum assignments. Run Edmonds-Karp. If it finds a flow that saturates the edges from tasks to sink, we are done. Otherwise we can increment the capacities from sink to workers in the residual graph and continue running Edmonds-Karp. Repeat until we saturate the edges into the sink. Don't increment the capacities so much that a worker is assigned too many tasks. Also, technically, the increment for each worker should be proportional to that worker's maximum assignments. These are both easy to do.

Finally let's meet requirement 6. This one is a bit tricky. First, add a column between workers and tasks and remove all edges from workers to tasks. In this new column, for each worker add a node for each of that workers interests. From each of these new nodes, add an edge to each task with a matching interest with capacity 1. Add an edge from each worker to each of its interest nodes with capacity 1. Now, a flow in this graph would enforce that if a worker is assigned to n tasks, then the intersection of the union of those task's interests with that worker's interests has size at least n. Again, it is possible that there is a satisfying assignment without this assignment, but there is not one with it. We can handle this the same as requirement 5: run Edmonds-Karp to completion, if no satisfying assignment, increment the capacities from workers to their interest nodes and repeat.

Note that in this modified graph we no longer satisfy requirement 3, as a single worker may be assigned to multiple/all slots of a task if the intersection of their interests has size greater than 1. We can fix that. Add a new column of nodes between the interest nodes and the task nodes and delete the edges between those nodes. For each employee, in the new column insert a node for each task (so each employee has its own node for each task). From these new nodes, to their corresponding task to the right, add an edge with capacity 1. From each worker's interests node to that worker's task nodes, add an edge with capacity 1 from each interest to each task that matches.

EDIT: Let me try to clarify this a little. Let -(n)-> be an edge with n capacity.

Previously we had worker-(1)->task for each worker-task pair with a matching interest. Now we have worker-(k)->local interest-(1)->local task-(1)->global task . Now, you can think of a task being matched to a worker-interest pair. The first edge says that for a worker, each of its interests can be matched to k tasks. The second edge says that each of a worker's interests can only be matched once to each job. The third edge says that each task can only be assigned once to each worker. Note that you could push multiple flow from the worker to a local task (equal to the size of the intersection of their interests) but only 1 flow from the worker to the global task node due to the third edge.

Also note that we can't really mix this incrementing with the one for requirement 5 correctly. However, we can run the whole algorithm once for each capacity {1,2,...,r} for worker->interest edges. We then need a way to rank the assignments. That is, as we relax requirement 5 we can better meet requirement 6 and vice versa. However, there is another approach that I prefer for relaxing these constraints.

A better approach to requirement relaxation (inspired-by/taken-from templatetypedef)

When we want to be able to relax multiple requirements (e.g. 5 and 6), we can model it as a min-cost max-flow problem. This may be simpler than the incremental search that I described above.

For example, for requirement 5, set all the edge costs to 0. We have the initial edge from the source to the worker with the capacity equal to worker's maximum assignments / (sum of all worker's maximum assignments / number of tasks) and with cost 0. Then you can add another edge with the remaining capacity for that worker and cost 1. Another possibility would be to use some sort of progressive cost such that as you add tasks to a worker the cost to add another task to that user goes up. E.g. you could instead split a worker's remaining capacity up into individual edges with costs 1,2,3,4,... .

A similar thing could then be done between the worker nodes and the local-interest nodes for requirement 6. The weighting would need to be balanced to reflect the relative importance of the different requirements.

This method is also sufficient to enforce requirement 4. Also, the costs for requirement 5 should probably be made such that they are proportional to a worker's maximum assignments. Then assigning 1 extra task to a worker with max 100 would not cost as much as assigning an extra to a worker with max 2.

Complexity Analysis

Let n = # of employees , m = # of tasks , k = max interests for a single task/worker , l = # of interests , j = maximum of maximum assignments .

Requirement 3 implies that n = O(m). Let's also assume that l = O(m) and j = O(m) .

In the smaller graph (before the change for req. 6), the graph has n + m + 2 = O(m) vertices and at most n + m + k*min(n, m) = O(km) edges.

After the change it has 2 + n + n * l + n * m + m = O(nm) vertices and n + k * n + k * m * n + n * m + m = O(kmn) edges (technically we may need j * n + j * l more nodes and edges so that there are not multiple edges from one node to another, but this wouldn't change the asymptotic bound). Also note that no edge need have capacity > j.

Using the min-cost max-flow formulation, we can find a solution in O(VEBlogV) where V = # vertices , E = # edges , and B = max capacity on a single edge . In our case this gives O(kjn^2m^2log(nm)) .

Chris Hopman's user avatar

  • There are standard algorithms for solving max-flow problems with lower-bounds on the flow on some edges; would that simplify the analysis and description a bit? Also, can you clarify how step six works? It seems like this could make some problems where legal assignments exist no longer have a solution. –  templatetypedef Commented Jan 22, 2011 at 21:51
  • Also, is there a reason for picking Edmonds-Karp instead of, say, a fast push-relabel variant? –  templatetypedef Commented Jan 22, 2011 at 22:26
  • I assumed Edmonds-Karp because I know it well. I do not know if the method that I used for satisfying requirement 4 will work with other algorithms. –  Chris Hopman Commented Jan 22, 2011 at 23:32
  • @templatetypedef I added a slight clarification for step six. If it is not clear, I can explain more. –  Chris Hopman Commented Jan 22, 2011 at 23:57
  • Wow, It's going to take some time to read through this answer! This is where a CS degree would have really helped. :) –  Jordan Reiter Commented Jan 25, 2011 at 6:15

For problems where finding a direct solution is difficult it can be a good idea to use an approximation algorithm, an evaulation function and a method to improve the solution. There are a variety of approaches, such as genetic algorithms and simulated annealing .

The basic idea is to use some sort of simple algorithm (such as a greedy algorithm) to get something that is vaguely usable and make random modifications, keeping those modifications that improve the evaluation score and discarding those that make it worse.

With genetic algorithms a group of for example 100 random solutions is generated and scored and the best are kept and "bred" to produce a new generation of solutions with characteristics similar to the previous generations, but with some random mutations.

For simulated annealing the probablility of a slightly worse solutions being accepted is high initially, but decreases over time. This reduces the risk of getting stuck at a local optimium early on.

Mark Byers's user avatar

Try mapping your task to the stable marriage problem . Tasks become prospective wives `, and your staff become suitors.

You might want to add some extra algorithm for assigning preferences of each task to the staff, and vice-versa - you could assign some ideal proficiency neccessary for the components of each task, and then allow your staff to rank each task. You could assign a proficiency for each component that each staff member posses and use that to get each tasks preference in staff members.

Once you have the preferences then run the algorithm, post the results, then allow people to apply in pairs to you to swap assignments - after all this is a people problem and people work better when they have a degree of control.

Paddy3118's user avatar

  • Actually, this is a "these are your tasks and you'll like them" problem -- this is not a scenario where the individual "workers" can pick and choose, the number of "workers" is huge, as are the number of "tasks" and as a result, changes after the fact really aren't feasible. That's why it's so crucial that we get it as right as possible the first time. –  Jordan Reiter Commented Jan 25, 2011 at 6:14
  • Then miss out the worker interaction sections. I've read that the stable marriage problem's solution algorithm is used to map interns to hospitals in the US, so it has the capacity. –  Paddy3118 Commented Jan 25, 2011 at 22:58
  • Coming in to finally mark one as an answer. Note that this isn't because the other two aren't also good answers, just that this one is probably the most straightforward to attempt. –  Jordan Reiter Commented Jul 7, 2011 at 15:55

So I gave this problem some thought and I think that you can get a good solution (for some definition of "good") by reducing it to an instance of min-cost max-flow (see this , for example). The idea is as follows. Suppose you are given as input a set of jobs J, each of which has a set of skills necessary, along with a set of workers W, each of whom has a set of talents. You are also given for each worker a constant k_i saying how many jobs you'd like them to do, as well as a constant m_i saying the maximum number of jobs you can allocate to them. Your goal is to assign the jobs to the workers in such a way that each job is done by a worker who has the skills, no worker does more than m_i jobs, and the number of the "excess" jobs done by the workers is minimized. For example, if the re are five workers who each want to do four tasks and the load is balanced so that two workers do four jobs, one does three, and one does five, the total excess is one, since one worker did one more job than was expected.

The reduction is as follows. For now, we'll ignore the balancing requirement and just see how tom reduce this to max-flow; we'll add load balancing at the end. Construct a graph G with a designated start node s and sink node t. Add to this graph a node for each job j and each worker w. There will be an edge from s to each of these j nodes of cost zero and capacity one. There will also be an edge from each w node to t with cost zero and capacity m_i. Finally, for each job j and worker w, if worker w has the talents necessary to complete job j, there is an edge from j to w with cost zero and capacity one.

The idea is that we want to push flow from s to t through the j and w nodes such that each flow path going through some j node to a w node means that job j should be given to worker w. The capacity restrictions on the edges from s to j nodes ensures that at most one unit of flow enters the j node, so the job is only assigned at most once. The capacity restriction on the edges from the w nodes to the node t prevent each worker from being assigned too many times. Since all capacities are integral, an integral max flow exists from s to t, and so a max-flow in this graph corresponds to an assignments of jobs to workers that is legal and doesn't exceed any worker's maximum load. You can check whether all jobs are assigned by looking at the total flow in the graph; if it's equal to the number of jobs, they've all been assigned.

This above construction, however, does nothing to balance worker loads. To fix this, we'll modify the construction a bit. Rather than having an edge from each w node to t, instead, for each w node, add two nodes to the graph, c and e, and connect them as follows. There is an edge from w_i to c_i with capacity k_i and cost zero, and an identical edge from c_i to t. There is also an edge from w_i to e_i with cost 1 and capacity m_i - k_i. There is also an edge from e_i to t with equal capacity and zero cost.

Intuitively, we haven't changed the amount of flow that leaves any w node, but we have changed how much that flow costs. Flow shunted to t via the c node is free, and so the worker can take on k_i jobs without incurring cost. Any jobs after that have to be routed through e, which costs one for each unit of flow crossing it. Finding a max-flow in this new graph still determines an assignment, but finding the min-cost max-flow in the graph finds the assignment that minimizes the excess jobs divvied up to workers.

Min-cost max flows can be solved in polynomial time with a few somewhat-well-known algorithms, so hopefully this is a useful answer!

templatetypedef's user avatar

  • Very nice solution (it should probably be the accepted answer, despite I don't see how it deals with the "variety of tasks" desired for the workers, but this is a relatively unimportant point). Also, I think that to satisfy the requirement of the OP that each job has to be taken by 3 workers, the edges from s to j should have capacity 3 (and not 1). –  MikeTeX Commented Dec 20, 2017 at 21:10

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged algorithm task or ask your own question .

  • Featured on Meta
  • Upcoming sign-up experiments related to tags
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • The [lib] tag is being burninated
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • Extending a local property of a measure to a global property of the measure.
  • How many steps are needed to turn one "a" into at least 100,000 "a"s using only the three functions of "select all", "copy" and "paste"?
  • Con permiso to enter your own house?
  • Automatic actions after starting addon?
  • How much is USA - Brazil?
  • How do I prevent losing the binoculars?
  • Why depreciation is considered a cost to own a car?
  • Can you help me to identify the aircraft in a 1920s photograph?
  • What type of black color text for brochure print in CMYK?
  • Single author or joint paper with a famous author?
  • How to engagingly introduce a ton of history that happens in, subjectively, a moment?
  • Would the command spell fail if the commanded action becomes directly harmful later on, but initially appears benign?
  • Is there a drawback to using Heart's blood rote repeatedly?
  • How is Victor Timely a variant of He Who Remains in the 19th century?
  • Predictable Network Interface Names: ensX vs enpXsY
  • What are these courtesy names and given names? - confusion in translation
  • What kind of sequence is between an arithmetic and a geometric sequence?
  • Is there any legal justification for content on the web without an explicit licence being freeware?
  • Summation not returning a timely result
  • What does ‘a grade-hog’ mean?
  • How to make D&D easier for kids?
  • Navigation on Mars without Martian GPS
  • Can I get a refund for ICE due to cancelled regional bus service?
  • PWM Dimming of a Low-Voltage DC Incandescent Filament (Thermal Shock?)

python assignment jobs

  • MapReduce Algorithm
  • Linear Programming using Pyomo
  • Networking and Professional Development for Machine Learning Careers in the USA
  • Predicting Employee Churn in Python
  • Airflow Operators

Machine Learning Geek

Solving Assignment Problem using Linear Programming in Python

Learn how to use Python PuLP to solve Assignment problems using Linear Programming.

In earlier articles, we have seen various applications of Linear programming such as transportation, transshipment problem, Cargo Loading problem, and shift-scheduling problem. Now In this tutorial, we will focus on another model that comes under the class of linear programming model known as the Assignment problem. Its objective function is similar to transportation problems. Here we minimize the objective function time or cost of manufacturing the products by allocating one job to one machine.

If we want to solve the maximization problem assignment problem then we subtract all the elements of the matrix from the highest element in the matrix or multiply the entire matrix by –1 and continue with the procedure. For solving the assignment problem, we use the Assignment technique or Hungarian method, or Flood’s technique.

The transportation problem is a special case of the linear programming model and the assignment problem is a special case of transportation problem, therefore it is also a special case of the linear programming problem.

In this tutorial, we are going to cover the following topics:

Assignment Problem

A problem that requires pairing two sets of items given a set of paired costs or profit in such a way that the total cost of the pairings is minimized or maximized. The assignment problem is a special case of linear programming.

For example, an operation manager needs to assign four jobs to four machines. The project manager needs to assign four projects to four staff members. Similarly, the marketing manager needs to assign the 4 salespersons to 4 territories. The manager’s goal is to minimize the total time or cost.

Problem Formulation

A manager has prepared a table that shows the cost of performing each of four jobs by each of four employees. The manager has stated his goal is to develop a set of job assignments that will minimize the total cost of getting all 4 jobs.  

Assignment Problem

Initialize LP Model

In this step, we will import all the classes and functions of pulp module and create a Minimization LP problem using LpProblem class.

Define Decision Variable

In this step, we will define the decision variables. In our problem, we have two variable lists: workers and jobs. Let’s create them using  LpVariable.dicts()  class.  LpVariable.dicts()  used with Python’s list comprehension.  LpVariable.dicts()  will take the following four values:

  • First, prefix name of what this variable represents.
  • Second is the list of all the variables.
  • Third is the lower bound on this variable.
  • Fourth variable is the upper bound.
  • Fourth is essentially the type of data (discrete or continuous). The options for the fourth parameter are  LpContinuous  or  LpInteger .

Let’s first create a list route for the route between warehouse and project site and create the decision variables using LpVariable.dicts() the method.

Define Objective Function

In this step, we will define the minimum objective function by adding it to the LpProblem  object. lpSum(vector)is used here to define multiple linear expressions. It also used list comprehension to add multiple variables.

Define the Constraints

Here, we are adding two types of constraints: Each job can be assigned to only one employee constraint and Each employee can be assigned to only one job. We have added the 2 constraints defined in the problem by adding them to the LpProblem  object.

Solve Model

In this step, we will solve the LP problem by calling solve() method. We can print the final value by using the following for loop.

From the above results, we can infer that Worker-1 will be assigned to Job-1, Worker-2 will be assigned to job-3, Worker-3 will be assigned to Job-2, and Worker-4 will assign with job-4.

In this article, we have learned about Assignment problems, Problem Formulation, and implementation using the python PuLp library. We have solved the Assignment problem using a Linear programming problem in Python. Of course, this is just a simple case study, we can add more constraints to it and make it more complicated. You can also run other case studies on Cargo Loading problems , Staff scheduling problems . In upcoming articles, we will write more on different optimization problems such as transshipment problem, balanced diet problem. You can revise the basics of mathematical concepts in  this article  and learn about Linear Programming  in this article .

  • Solving Blending Problem in Python using Gurobi
  • Transshipment Problem in Python Using PuLP

You May Also Like

python assignment jobs

Solving Staff Scheduling Problem using Linear Programming

python assignment jobs

Python Generators

python assignment jobs

Python Decorators

Python Practice Problems: Prepare for Your Next Interview

Python Practice Problems: Get Ready for Your Next Interview

Table of Contents

Problem Description

Problem solution.

Are you a Python developer brushing up on your skills before an interview ? If so, then this tutorial will usher you through a series of Python practice problems meant to simulate common coding test scenarios. After you develop your own solutions, you’ll walk through the Real Python team’s answers so you can optimize your code, impress your interviewer, and land your dream job!

In this tutorial, you’ll learn how to:

  • Write code for interview-style problems
  • Discuss your solutions during the interview
  • Work through frequently overlooked details
  • Talk about design decisions and trade-offs

This tutorial is aimed at intermediate Python developers. It assumes a basic knowledge of Python and an ability to solve problems in Python. You can get skeleton code with failing unit tests for each of the problems you’ll see in this tutorial by clicking on the link below:

Download the sample code: Click here to get the code you’ll use to work through the Python practice problems in this tutorial.

Each of the problems below shows the file header from this skeleton code describing the problem requirements. So download the code, fire up your favorite editor, and let’s dive into some Python practice problems!

Python Practice Problem 1: Sum of a Range of Integers

Let’s start with a warm-up question. In the first practice problem, you’ll write code to sum a list of integers . Each practice problem includes a problem description. This description is pulled directly from the skeleton files in the repo to make it easier to remember while you’re working on your solution.

You’ll see a solution section for each problem as well. Most of the discussion will be in a collapsed section below that. Clone that repo if you haven’t already, work out a solution to the following problem, then expand the solution box to review your work.

Here’s your first problem:

Sum of Integers Up To n ( integersums.py ) Write a function, add_it_up() , that takes a single integer as input and returns the sum of the integers from zero to the input parameter. The function should return 0 if a non-integer is passed in.

Remember to run the unit tests until you get them passing!

Here’s some discussion of a couple of possible solutions.

Note: Remember, don’t open the collapsed section below until you’re ready to look at the answer for this Python practice problem!

Solution for Sum of a Range of Integers Show/Hide

How did writing the solution go? Ready to look at the answer?

For this problem, you’ll look at a few different solutions. The first of these is not so good:

In this solution, you manually build a while loop to run through the numbers 1 through n . You keep a running sum and then return it when you’ve finished the loop.

This solution works, but it has two problems:

It doesn’t display your knowledge of Python and how the language simplifies tasks like this.

It doesn’t meet the error conditions in the problem description. Passing in a string will result in the function throwing an exception when it should just return 0 .

You’ll deal with the error conditions in the final answer below, but first let’s refine the core solution to be a bit more Pythonic .

The first thing to think about is that while loop . Python has powerful mechanisms for iterating over lists and ranges. Creating your own is usually unnecessary, and that’s certainly the case here. You can replace the while loop with a loop that iterates over a range() :

You can see that the for...range() construct has replaced your while loop and shortened the code. One thing to note is that range() goes up to but does not include the number given, so you need to use n + 1 here.

This was a nice step! It removes some of the boilerplate code of looping over a range and makes your intention clearer. But there’s still more you can do here.

Summing a list of integers is another thing Python is good at:

Wow! By using the built-in sum() , you got this down to one line of code! While code golf generally doesn’t produce the most readable code, in this case you have a win-win: shorter and more readable code.

There’s one problem remaining, however. This code still doesn’t handle the error conditions correctly. To fix that, you can wrap your previous code in a try...except block:

This solves the problem and handles the error conditions correctly. Way to go!

Occasionally, interviewers will ask this question with a fixed limit, something like “Print the sum of the first nine integers.” When the problem is phrased that way, one correct solution would be print(45) .

If you give this answer, however, then you should follow up with code that solves the problem step by step. The trick answer is a good place to start your answer, but it’s not a great place to end.

If you’d like to extend this problem, try adding an optional lower limit to add_it_up() to give it more flexibility!

Python Practice Problem 2: Caesar Cipher

The next question is a two-parter. You’ll code up a function to compute a Caesar cipher on text input. For this problem, you’re free to use any part of the Python standard library to do the transform.

Hint: There’s a function in the str class that will make this task much easier!

The problem statement is at the top of the skeleton source file:

Caesar Cipher ( caesar.py ) A Caesar cipher is a simple substitution cipher in which each letter of the plain text is substituted with a letter found by moving n places down the alphabet. For example, assume the input plain text is the following: abcd xyz If the shift value, n , is 4, then the encrypted text would be the following: efgh bcd You are to write a function that accepts two arguments, a plain-text message and a number of letters to shift in the cipher. The function will return an encrypted string with all letters transformed and all punctuation and whitespace remaining unchanged. Note: You can assume the plain text is all lowercase ASCII except for whitespace and punctuation.

Remember, this part of the question is really about how well you can get around in the standard library. If you find yourself figuring out how to do the transform without the library, then save that thought! You’ll need it later!

Here’s a solution to the Caesar cipher problem described above.

Note: Remember, don’t open the collapsed section below until you’re ready to look at the answers for this Python practice problem!

Solution for Caesar Cipher Show/Hide

This solution makes use of .translate() from the str class in the standard library. If you struggled with this problem, then you might want to pause a moment and consider how you could use .translate() in your solution.

Okay, now that you’re ready, let’s look at this solution:

You can see that the function makes use of three things from the string module:

  • .ascii_lowercase
  • .maketrans()
  • .translate()

In the first two lines, you create a variable with all the lowercase letters of the alphabet (ASCII only for this program) and then create a mask , which is the same set of letters, only shifted. The slicing syntax is not always obvious, so let’s walk through it with a real-world example:

You can see that x[3:] is all the letters after the third letter, 'c' , while x[:3] is just the first three letters.

Line 6 in the solution, letters[shift_num:] + letters[:shift_num] , creates a list of letters shifted by shift_num letters, with the letters at the end wrapped around to the front. Once you have the list of letters and the mask of letters you want to map to, you call .maketrans() to create a translation table.

Next, you pass the translation table to the string method .translate() . It maps all characters in letters to the corresponding letters in mask and leaves all other characters alone.

This question is an exercise in knowing and using the standard library. You may be asked a question like this at some point during an interview. If that happens to you, it’s good to spend some time thinking about possible answers. If you can remember the method— .translate() in this case—then you’re all set.

But there are a couple of other scenarios to consider:

You may completely draw a blank. In this case, you’ll probably solve this problem the way you solve the next one , and that’s an acceptable answer.

You may remember that the standard library has a function to do what you want but not remember the details.

If you were doing normal work and hit either of these situations, then you’d just do some searching and be on your way. But in an interview situation, it will help your cause to talk through the problem out loud.

Asking the interviewer for specific help is far better than just ignoring it. Try something like “I think there’s a function that maps one set of characters to another. Can you help me remember what it’s called?”

In an interview situation, it’s often better to admit that you don’t know something than to try to bluff your way through.

Now that you’ve seen a solution using the Python standard library, let’s try the same problem again, but without that help!

Python Practice Problem 3: Caesar Cipher Redux

For the third practice problem, you’ll solve the Caesar cipher again, but this time you’ll do it without using .translate() .

The description of this problem is the same as the previous problem. Before you dive into the solution, you might be wondering why you’re repeating the same exercise, just without the help of .translate() .

That’s a great question. In normal life, when your goal is to get a working, maintainable program, rewriting parts of the standard library is a poor choice. The Python standard library is packed with working, well-tested, and fast solutions for problems large and small. Taking full advantage of it is a mark of a good programmer.

That said, this is not a work project or a program you’re building to satisfy a need. This is a learning exercise, and it’s the type of question that might be asked during an interview. The goal for both is to see how you can solve the problem and what interesting design trade-offs you make while doing it.

So, in the spirit of learning, let’s try to resolve the Caesar cipher without .translate() .

For this problem, you’ll have two different solutions to look at when you’re ready to expand the section below.

Solutions for Caesar Cipher Redux Show/Hide

For this problem, two different solutions are provided. Check out both and see which one you prefer!

For the first solution, you follow the problem description closely, adding an amount to each character and flipping it back to the beginning of the alphabet when it goes on beyond z :

Starting on line 14, you can see that caesar() does a list comprehension , calling a helper function for each letter in message . It then does a .join() to create the new encoded string. This is short and sweet, and you’ll see a similar structure in the second solution. The interesting part happens in shift_n() .

Here you can see another use for string.ascii_lowercase , this time filtering out any letter that isn’t in that group. Once you’re certain you’ve filtered out any non-letters, you can proceed to encoding. In this version of encoding, you use two functions from the Python standard library:

Again, you’re encouraged not only to learn these functions but also to consider how you might respond in an interview situation if you couldn’t remember their names.

ord() does the work of converting a letter to a number, and chr() converts it back to a letter. This is handy as it allows you to do arithmetic on letters, which is what you want for this problem.

The first step of your encoding on line 7 gets the numeric value of the encoded letter by using ord() to get the numeric value of the original letter. ord() returns the Unicode code point of the character, which turns out to be the ASCII value.

For many letters with small shift values, you can convert the letter back to a character and you’ll be done. But consider the starting letter, z .

A shift of one character should result in the letter a . To achieve this wraparound, you find the difference from the encoded letter to the letter z . If that difference is positive, then you need to wrap back to the beginning.

You do this in lines 8 to 11 by repeatedly adding 26 to or subtracting it from the character until it’s in the range of ASCII characters. Note that this is a fairly inefficient method for fixing this issue. You’ll see a better solution in the next answer.

Finally, on line 12, your conversion shift function takes the numeric value of the new letter and converts it back to a letter to return it.

While this solution takes a literal approach to solving the Caesar cipher problem, you could also use a different approach modeled after the .translate() solution in practice problem 2 .

The second solution to this problem mimics the behavior of Python’s built-in method .translate() . Instead of shifting each letter by a given amount, it creates a translation map and uses it to encode each letter:

Starting with caesar() on line 11, you start by fixing the problem of amount being greater than 26 . In the previous solution, you looped repeatedly until the result was in the proper range. Here, you take a more direct and more efficient approach using the mod operator ( % ).

The mod operator produces the remainder from an integer division. In this case, you divide by 26 , which means the results are guaranteed to be between 0 and 25 , inclusive.

Next, you create the translation table. This is a change from the previous solutions and is worth some attention. You’ll see more about this toward the end of this section.

Once you create the table , the rest of caesar() is identical to the previous solution: a list comprehension to encrypt each letter and a .join() to create a string.

shift_n() finds the index of the given letter in the alphabet and then uses this to pull a letter from the table . The try...except block catches those cases that aren’t found in the list of lowercase letters.

Now let’s discuss the table creation issue. For this toy example, it probably doesn’t matter too much, but it illustrates a situation that occurs frequently in everyday development: balancing clarity of code against known performance bottlenecks.

If you examine the code again, you’ll see that table is used only inside shift_n() . This indicates that, in normal circumstances, it should have been created in, and thus have its scope limited to, shift_n() :

The issue with that approach is that it spends time calculating the same table for every letter of the message. For small messages, this time will be negligible, but it might add up for larger messages.

Another possible way that you could avoid this performance penalty would be to make table a global variable . While this also cuts down on the construction penalty, it makes the scope of table even larger. This doesn’t seem better than the approach shown above.

At the end of the day, the choice between creating table once up front and giving it a larger scope or just creating it for every letter is what’s called a design decision . You need to choose the design based on what you know about the actual problem you’re trying to solve.

If this is a small project and you know it will be used to encode large messages, then creating the table only once could be the right decision. If this is only a portion of a larger project, meaning maintainability is key, then perhaps creating the table each time is the better option.

Since you’ve looked at two solutions, it’s worth taking a moment to discuss their similarities and differences.

Solution Comparison

You’ve seen two solutions in this part of the Caesar cipher, and they’re fairly similar in many ways. They’re about the same number of lines. The two main routines are identical except for limiting amount and creating table . It’s only when you look at the two versions of the helper function, shift_n() , that the differences appear.

The first shift_n() is an almost literal translation of what the problem is asking for: “Shift the letter down the alphabet and wrap it around at z .” This clearly maps back to the problem statement, but it has a few drawbacks.

Although it’s about the same length as the second version, the first version of shift_n() is more complex. This complexity comes from the letter conversion and math needed to do the translation. The details involved—converting to numbers, subtracting, and wrapping—mask the operation you’re performing. The second shift_n() is far less involved in its details.

The first version of the function is also specific to solving this particular problem. The second version of shift_n() , like the standard library’s .translate() that it’s modeled after, is more general-purpose and can be used to solve a larger set of problems. Note that this is not necessarily a good design goal.

One of the mantras that came out of the Extreme Programming movement is “You aren’t gonna need it” (YAGNI). Frequently, software developers will look at a function like shift_n() and decide that it would be better and more general-purpose if they made it even more flexible, perhaps by passing in a parameter instead of using string.ascii_lowercase .

While that would indeed make the function more general-purpose, it would also make it more complex. The YAGNI mantra is there to remind you not to add complexity before you have a specific use case for it.

To wrap up your Caesar cipher section, there are clear trade-offs between the two solutions, but the second shift_n() seems like a slightly better and more Pythonic function.

Now that you’ve written the Caesar cipher three different ways, let’s move on to a new problem.

Python Practice Problem 4: Log Parser

The log parser problem is one that occurs frequently in software development. Many systems produce log files during normal operation, and sometimes you’ll need to parse these files to find anomalies or general information about the running system.

For this problem, you’ll need to parse a log file with a specified format and generate a report:

Log Parser ( logparse.py ) Accepts a filename on the command line. The file is a Linux-like log file from a system you are debugging. Mixed in among the various statements are messages indicating the state of the device. They look like this: Jul 11 16:11:51:490 [139681125603136] dut: Device State: ON The device state message has many possible values, but this program cares about only three: ON , OFF , and ERR . Your program will parse the given log file and print out a report giving how long the device was ON and the timestamp of any ERR conditions.

Note that the provided skeleton code doesn’t include unit tests. This was omitted since the exact format of the report is up to you. Think about and write your own during the process.

A test.log file is included, which provides you with an example. The solution you’ll examine produces the following output:

While that format is generated by the Real Python solution, you’re free to design your own format for the output. The sample input file should generate equivalent information.

In the collapsed section below, you’ll find a possible solution to the log parser problem. When you’re ready, expand the box and compare it with what you came up with!

Solution for Log Parser Problem Show/Hide

Full Solution

Since this solution is longer than what you saw for the integer sums or the Caesar cipher problems, let’s start with the full program:

That’s your full solution. You can see that the program consists of three functions and the main section. You’ll work through them from the top.

Helper Function: get_next_event()

First up is get_next_event() :

Because it contains a yield statement, this function is a generator . That means you can use it to generate one event from the log file at a time.

You could have just used for line in datafile , but instead you add a little bit of filtering. The calling routine will get only those events that have dut: Device State: in them. This keeps all the file-specific parsing contained in a single function.

This might make get_next_event() a bit more complicated, but it’s a relatively small function, so it remains short enough to read and comprehend. It also keeps that complicated code encapsulated in a single location.

You might be wondering when datafile gets closed. As long as you call the generator until all of the lines are read from datafile , the for loop will complete, allowing you to leave the with block and exit from the function.

Helper Function: compute_time_diff_seconds()

The second function is compute_time_diff_seconds() , which, as the name suggests, computes the number of seconds between two timestamps:

There are a few interesting points to this function. The first is that subtracting the two datetime objects results in a datetime.timedelta . For this problem, you will report total seconds, so returning .total_seconds() from the timedelta is appropriate.

The second item of note is that there are many, many packages in Python that simplify handling dates and times. In this case, your use model is simple enough that it doesn’t warrant the complexity of pulling in an external library when the standard library functions will suffice.

That said, datetime.datetime.strptime() is worthy of mention. When passed a string and a specific format, .strptime() parses that string with the given format and produces a datetime object.

This is another place where, in an interview situation, it’s important not to panic if you can’t remember the exact names of the Python standard library functions.

Helper Function: extract_data()

Next up is extract_data() , which does the bulk of the work in this program. Before you dive into the code, let’s step back and talk about state machines.

State machines are software (or hardware) devices that transition from one state to another depending on specific inputs. That’s a really broad definition that might be difficult to grasp, so let’s look at a diagram of the state machine you’ll be using below:

State machine with two states: ON and OFF with transitions between the states.

In this diagram, the states are represented by the labeled boxes. There are only two states here, ON and OFF , which correspond to the state of the device. There are also two input signals, Device State: ON and Device State: OFF . The diagram uses arrows to show what happens when an input occurs while the machine is in each state.

For example, if the machine is in the ON state and the Device State: ON input occurs, then the machine stays in the ON state. No change happens. Conversely, if the machine receives the Device State: OFF input when it’s in the ON state, then it will transition to the OFF state.

While the state machine here is only two states with two inputs, state machines are often much more complex. Creating a diagram of expected behavior can help you make the code that implements the state machine more concise.

Let’s move back to extract_data() :

It might be hard to see the state machine here. Usually, state machines require a variable to hold the state. In this case, you use time_on_started to serve two purposes:

  • Indicate state: time_on_started holds the state of your state machine. If it’s None , then the machine is in the OFF state. If it’s not None , then the machine is ON .
  • Store start time: If the state is ON , then time_on_started also holds the timestamp of when the device turned on. You use this timestamp to call compute_time_diff_seconds() .

The top of extract_data() sets up your state variable, time_on_started , and also the two outputs you want. errs is a list of timestamps at which the ERR message was found, and total_time_on is the sum of all periods when the device was on.

Once you’ve completed the initial setup, you call the get_next_event() generator to retrieve each event and timestamp. The action it receives is used to drive the state machine, but before it checks for state changes, it first uses an if block to filter out any ERR conditions and add those to errs .

After the error check, the first elif block handles transitions to the ON state. You can transition to ON only when you’re in the OFF state, which is signaled by time_on_started being False . If you’re not already in the ON state and the action is "ON" , then you store the timestamp , putting the machine into the ON state.

The second elif handles the transition to the OFF state. On this transition, extract_data() needs to compute the number of seconds the device was on. It does this using the compute_time_diff_seconds() you saw above. It adds this time to the running total_time_on and sets time_on_started back to None , effectively putting the machine back into the OFF state.

Main Function

Finally, you can move on to the __main__ section. This final section passes sys.argv[1] , which is the first command-line argument , to extract_data() and then presents a report of the results:

To call this solution, you run the script and pass the name of the log file. Running your example code results in this output:

Your solution might have different formatting, but the information should be the same for the sample log file.

There are many ways to solve a problem like this. Remember that in an interview situation, talking through the problem and your thought process can be more important than which solution you choose to implement.

That’s it for the log-parsing solution. Let’s move on to the final challenge: sudoku!

Python Practice Problem 5: Sudoku Solver

Your final Python practice problem is to solve a sudoku puzzle!

Finding a fast and memory-efficient solution to this problem can be quite a challenge. The solution you’ll examine has been selected for readability rather than speed, but you’re free to optimize your solution as much as you want.

The description for the sudoku solver is a little more involved than the previous problems:

Sudoku Solver ( sudokusolve.py ) Given a string in SDM format, described below, write a program to find and return the solution for the sudoku puzzle in the string. The solution should be returned in the same SDM format as the input. Some puzzles will not be solvable. In that case, return the string “Unsolvable”. The general SDM format is described here . For our purposes, each SDM string will be a sequence of 81 digits, one for each position on the sudoku puzzle. Known numbers will be given, and unknown positions will have a zero value. For example, assume you’re given this string of digits: 004006079000000602056092300078061030509000406020540890007410920105000000840600100 The string represents this starting sudoku puzzle: 0 0 4 0 0 6 0 7 9 0 0 0 0 0 0 6 0 2 0 5 6 0 9 2 3 0 0 0 7 8 0 6 1 0 3 0 5 0 9 0 0 0 4 0 6 0 2 0 5 4 0 8 9 0 0 0 7 4 1 0 9 2 0 1 0 5 0 0 0 0 0 0 8 4 0 6 0 0 1 0 0 The provided unit tests may take a while to run, so be patient. Note: A description of the sudoku puzzle can be found on Wikipedia .

You can see that you’ll need to deal with reading and writing to a particular format as well as generating a solution.

When you’re ready, you can find a detailed explanation of a solution to the sudoku problem in the box below. A skeleton file with unit tests is provided in the repo.

Solution for Sudoku Solver Show/Hide

This is a larger and more complex problem than you’ve looked at so far in this tutorial. You’ll walk through the problem step by step, ending with a recursive function that solves the puzzle. Here’s a rough outline of the steps you’ll take:

  • Read the puzzle into a grid form.
  • Place the number in the cell.
  • Remove that number from the row, column, and small square.
  • Move to the next position.
  • If no possible numbers remain, then declare the puzzle unsolvable .
  • If all cells are filled, then return the solution .

The tricky part of this algorithm is keeping track of the grid at each step of the process. You’ll use recursion, making a new copy of the grid at each level of the recursion, to maintain this information.

With that outline in mind, let’s start with the first step, creating the grid.

Generating a Grid From a Line

To start, it’s helpful to convert the puzzle data into a more usable format. Even if you eventually want to solve the puzzle in the given SDM format , you’ll likely make faster progress working through the details of your algorithm with the data in a grid form. Once you have a solution that works, then you can convert it to work on a different data structure.

To this end, let’s start with a couple of conversion functions:

Your first function, line_to_grid() , converts the data from a single string of eighty-one digits to a list of lists. For example, it converts the string line to a grid like start :

Each inner list here represents a horizontal row in your sudoku puzzle.

You start with an empty grid and an empty line . You then build each line by converting nine characters from the values string to single-digit integers and then appending them to the current line . Once you have nine values in a line , as indicated by index % 9 == 0 on line 7, you insert that line into the grid and start a new one.

The function ends by appending the final line to the grid . You need this because the for loop will end with the last line still stored in the local variable and not yet appended to grid .

The inverse function, grid_to_line() , is slightly shorter. It uses a generator expression with .join() to create a nine-digit string for each row. It then appends that string to the overall line and returns it. Note that it’s possible to use nested generators to create this result in fewer lines of code, but the readability of the solution starts to fall off dramatically.

Now that you’ve got the data in the data structure you want, let’s start working with it.

Generating a Small Square Iterator

Your next function is a generator that will help you search for the smaller three-by-three square a given position is in. Given the x- and y-coordinates of the cell in question, this generator will produce a list of coordinates that match the square that contains it:

A Sudoku grid with one of the small squares highlighted.

In the image above, you’re examining cell (3, 1) , so your generator will produce coordinate pairs corresponding to all the lightly shaded cells, skipping the coordinates that were passed in:

Putting the logic for determining this small square in a separate utility function keeps the flow of your other functions more readable. Making this a generator allows you to use it in a for loop to iterate through each of the values.

The function to do this involves using the limitations of integer math:

There are a lot of threes in a couple of those lines, which makes lines like ((x + 3) // 3) * 3 look confusing. Here’s what happens when x is 1 .

Using the rounding of integer math allows you to get the next-highest multiple of three above a given value. Once you have this, subtracting three will give you the multiple of three below the given number.

There are a few more low-level utility functions to examine before you start building on top of them.

Moving to the Next Spot

Your solution will need to walk through the grid structure one cell at a time. This means that at some point, you’ll need to figure out what the next position should be. compute_next_position() to the rescue!

compute_next_position() takes the current x- and y-coordinates as input and returns a tuple containing a finished flag along with the x- and y-coordinates of the next position:

The finished flag tells the caller that the algorithm has walked off the end of the puzzle and has completed all the squares. You’ll see how that’s used in a later section.

Removing Impossible Numbers

Your final low-level utility is quite small. It takes an integer value and an iterable. If the value is nonzero and appears in the iterable, then the function removes it from the iterable:

Typically, you wouldn’t make this small bit of functionality into a function. You’ll use this function several times, though, so it’s best to follow the DRY principle and pull it up to a function.

Now you’ve seen the bottom level of the functionality pyramid. It’s time to step up and use those tools to build a more complex function. You’re almost ready to solve the puzzle!

Finding What’s Possible

Your next function makes use of some of the low-level functions you’ve just walked through. Given a grid and a position on that grid, it determines what values that position could still have:

A Sudoku grid showing a starting point to indicate possible values for a specific cell.

For the grid above, at the position (3, 1) , the possible values are [1, 5, 8] because the other values are all present, either in that row or column or in the small square you looked at earlier.

This is the responsibility of detect_possible() :

The function starts by checking if the given position at x and y already has a nonzero value. If so, then that’s the only possible value and it returns.

If not, then the function creates a set of the numbers one through nine. The function proceeds to check different blocking numbers and removes those from this set.

It starts by checking the column and row of the given position. This can be done with a single loop by just alternating which subscript changes. grid[x][index] checks values in the same column, while grid[index][y] checks those values in the same row. You can see that you’re using test_and_remove() here to simplify the code.

Once those values have been removed from your possible set, the function moves on to the small square. This is where the small_square() generator you created before comes in handy. You can use it to iterate over each position in the small square, again using test_and_remove() to eliminate any known values from your possible list.

Once all the known blocking values have been removed from your set, you have the list of all possible values for that position on that grid.

You might wonder why the code and its description make a point about the position being “on that grid.” In your next function, you’ll see that the program makes many copies of the grid as it tries to solve it.

You’ve reached the heart of this solution: solve() ! This function is recursive, so a little up-front explanation might help.

The general design of solve() is based on testing a single position at a time. For the position of interest, the algorithm gets the list of possible values and then selects those values, one at a time, to be in this position.

For each of these values, it creates a grid with the guessed value in this position. It then calls a function to test for a solution, passing in the new grid and the next position.

It just so happens that the function it calls is itself.

For any recursion, you need a termination condition. This algorithm has four of them:

  • There are no possible values for this position. That indicates the solution it’s testing can’t work.
  • It’s walked to the end of the grid and found a possible value for each position. The puzzle is solved!
  • One of the guesses at this position, when passed back to the solver, returns a solution.
  • It’s tried all possible values at this position and none of them will work.

Let’s look at the code for this and see how it all plays out:

The first thing to note in this function is that it makes a .deepcopy() of the grid. It does a deep copy because the algorithm needs to keep track of exactly where it was at any point in the recursion. If the function made only a shallow copy, then every recursive version of this function would use the same grid.

Once the grid is copied, solve() can work with the new copy, temp . A position on the grid was passed in, so that’s the number that this version of the function will solve. The first step is to see what values are possible in this position. As you saw earlier, detect_possible() returns a list of possible values that may be empty.

If there are no possible values, then you’ve hit the first termination condition for the recursion. The function returns False , and the calling routine moves on.

If there are possible values, then you need to move on and see if any of them is a solution. Before you do that, you can add a little optimization to the code. If there’s only a single possible value, then you can insert that value and move on to the next position. The solution shown does this in a loop, so you can place multiple numbers into the grid without having to recur.

This may seem like a small improvement, and I’ll admit my first implementation did not include this. But some testing showed that this solution was dramatically faster than simply recurring here at the price of more complex code.

Note: This is an excellent point to bring up during an interview even if you don’t add the code to do this. Showing them that you’re thinking about trading off speed against complexity is a strong positive signal to interviewers.

Sometimes, of course, there will be multiple possible values for the current position, and you’ll need to decide if any of them will lead to a solution. Fortunately, you’ve already determined the next position in the grid, so you can forgo placing the possible values.

If the next position is off the end of the grid, then the current position is the final one to fill. If you know that there’s at least one possible value for this position, then you’ve found a solution! The current position is filled in and the completed grid is returned up to the calling function.

If the next position is still on the grid, then you loop through each possible value for the current spot, filling in the guess at the current position and then calling solve() with the temp grid and the new position to test.

solve() can return only a completed grid or False , so if any of the possible guesses returns a result that isn’t False , then a result has been found, and that grid can be returned up the stack.

If all possible guesses have been made and none of them is a solution, then the grid that was passed in is unsolvable. If this is the top-level call, then that means the puzzle is unsolvable. If the call is lower in the recursion tree, then it just means that this branch of the recursion tree isn’t viable.

Putting It All Together

At this point, you’re almost through the solution. There’s only one final function left, sudoku_solve() :

This function does three things:

  • Converts the input string into a grid
  • Calls solve() with that grid to get a solution
  • Returns the solution as a string or "Unsolvable" if there’s no solution

That’s it! You’ve walked through a solution for the sudoku solver problem.

Interview Discussion Topics

The sudoku solver solution you just walked through is a good deal of code for an interview situation. Part of an interview process would likely be to discuss some of the code and, more importantly, some of the design trade-offs you made. Let’s look at a few of those trade-offs.

The biggest design decision revolves around using recursion. It’s possible to write a non-recursive solution to any problem that has a recursive solution. Why choose recursion over another option?

This is a discussion that depends not only on the problem but also on the developers involved in writing and maintaining the solution. Some problems lend themselves to rather clean recursive solutions, and some don’t.

In general, recursive solutions will take more time to run and use more memory than non-recursive solutions. But that’s not always true and, more importantly, it’s not always important .

Similarly, some teams of developers are comfortable with recursive solutions, while others find them exotic or unnecessarily complex. Maintainability should play into your design decisions as well.

One good discussion to have about a decision like this is around performance. How fast does this solution need to execute? Will it be used to solve billions of puzzles or just a handful? Will it run on a small embedded system with memory constraints, or will it be on a large server?

These external factors can help you decide which is a better design decision. These are great topics to bring up in an interview as you’re working through a problem or discussing code. A single product might have places where performance is critical (doing ray tracing on a graphics algorithm, for example) and places where it doesn’t matter at all (such as parsing the version number during installation).

Bringing up topics like this during an interview shows that you’re not only thinking about solving an abstract problem, but you’re also willing and able to take it to the next level and solve a specific problem facing the team.

Readability and Maintainability

Sometimes it’s worth picking a solution that’s slower in order to make a solution that’s easier to work with, debug, and extend. The decision in the sudoku solver challenge to convert the data structure to a grid is one of those decisions.

That design decision likely slows down the program, but unless you’ve measured, you don’t know. Even if it does, putting the data structure into a form that’s natural for the problem can make the code easier to comprehend.

It’s entirely possible to write a solver that operates on the linear strings you’re given as input. It’s likely faster and probably takes less memory, but small_square() , among others, will be a lot harder to write, read, and maintain in this version.

Another thing to discuss with an interviewer, whether you’re live coding or discussing code you wrote offline, is the mistakes and false turns you took along the way.

This is a little less obvious and can be slightly detrimental, but particularly if you’re live coding, taking a step to refactor code that isn’t right or could be better can show how you work. Few developers can write perfect code the first time. Heck, few developers can write good code the first time.

Good developers write the code, then go back and refactor it and fix it. For example, my first implementation of detect_possible() looked like this:

Ignoring that it doesn’t consider the small_square() information, this code can be improved. If you compare this to the final version of detect_possible() above, you’ll see that the final version uses a single loop to test both the horizontal and the vertical dimensions.

Wrapping Up

That’s your tour through a sudoku solver solution. There’s more information available on formats for storing puzzles and a huge list of sudoku puzzles you can test your algorithm on.

That’s the end of your Python practice problems adventure! But if you’d like more, head on over to the video course Write and Test a Python Function: Interview Practice to see an experienced developer tackle an interview problem in real time.

Congratulations on working through this set of Python practice problems! You’ve gotten some practice applying your Python skills and also spent some time thinking about how you can respond in different interviewing situations.

In this tutorial, you learned how to:

Remember, you can download the skeleton code for these problems by clicking on the link below:

Feel free to reach out in the comments section with any questions you have or suggestions for other Python practice problems you’d like to see! Also check out our “Ace Your Python Coding Interview” Learning Path to get more resources and for boosting your Python interview skills.

Good luck with the interview!

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Jim Anderson

Jim Anderson

Jim has been programming for a long time in a variety of languages. He has worked on embedded systems, built distributed build systems, done off-shore vendor management, and sat in many, many meetings.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Aldren Santos

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal . Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session . Happy Pythoning!

Keep Learning

Related Topics: intermediate best-practices career

Keep reading Real Python by creating a free account or signing in:

Already have an account? Sign-In

Almost there! Complete this form and click the button below to gain instant access:

Python Practice Problems Sample Code

🔒 No spam. We take your privacy seriously.

python assignment jobs

Currently Reading :

Currently reading:

Simple assignment operator in Python

Different assignment operators in python.

Rajat Gupta

Software Developer

Published on  Thu Jun 30 2022

Assignment operators in Python are in-fix which are used to perform operations on variables or operands and assign values to the operand on the left side of the operator. They perform arithmetic, logical, and bitwise computations.

Assignment Operators in Python

Add and equal operator, subtract and equal operator, multiply and equal operator, divide and equal operator, modulus and equal operator, double divide and equal operator, exponent assign operator.

  • Bitwise and operator

Bitwise OR operator

  • Bitwise XOR Assignment operator

Bitwise right shift assignment operator

Bitwise left shift assignment operator.

The Simple assignment operator in Python is denoted by = and is used to assign values from the right side of the operator to the value on the left side.

This operator adds the value on the right side to the value on the left side and stores the result in the operand on the left side.

This operator subtracts the value on the right side from the value on the left side and stores the result in the operand on the left side.

The Multiply and equal operator multiplies the right operand with the left operand and then stores the result in the left operand.

It divides the left operand with the right operand and then stores the quotient in the left operand.

The modulus and equal operator finds the modulus from the left and right operand and stores the final result in the left operand.

The double divide and equal or the divide floor and equal operator divides the left operand with the right operand and stores the floor result in the left operand.

It performs exponential or power calculation and assigns value to the left operand.

Bitwise And operator

Performs Bitwise And operation on both variables and stores the result in the left operand. The Bitwise And operation compares the corresponding bits of the left operand to the bits of the right operand and if both bits are 1, the corresponding result is also 1 otherwise 0.

The binary value of 3 is 0011 and the binary value of 5 is 0101, so when the Bitwise And operation is performed on both the values, we get 0001, which is 1 in decimal.

Performs Bitwise OR operator on both variables and stores the result in the left operand. The Bitwise OR operation compares the corresponding bits of the left operand to the bits of the right operand and if any one of the bits is 1, the corresponding result is also 1 otherwise 0.

The binary value of 5 is 0101 and the binary value of 10 is 1010, so when the Bitwise OR operation is performed on both the values, we get 1111, which is 15 in decimal .

Bitwise XOR operator

Performs Bitwise XOR operator on both variables and stores the result in the left operand. The Bitwise XOR operation compares the corresponding bits of the left operand to the bits of the right operand and if only one of the bits is 1, the corresponding result is also 1 otherwise 0.

The binary value of 5 is 0101 and the binary value of 9 is 1001, so when the Bitwise XOR operation is performed on both the values, we get 1100, which is 12 in decimal.

This operator performs a Bitwise right shift on the operands and stores the result in the left operand.

The binary value of 15 is 1111, so when the Bitwise right shift operation is performed on ‘a’, we get 0011, which is 3 in decimal.

This operator performs a Bitwise left shift on the operands and stores the result in the left operand.

The binary value of 15 is 1111, so when the Bitwise left shift operation is performed on ‘a’, we get 11110, which is 30 in decimal.

Closing Thoughts

In this tutorial, we read about different types of assignment operators in Python which are special symbols used to perform arithmetic, logical, and bitwise operations on the operands and store the result in the left side operand. One can read about other Python concepts here .

About the author

Rajat Gupta is an experienced financial analyst known for his deep insights into market trends and investment strategies. He excels in providing robust financial solutions that drive growth and stability.

Related Blogs

4 Ways to implement Python Switch Case Statement

Sanchitee Ladole

Converting String to Float in Python

Ancil Eric D'Silva

Memoization Using Decorators In Python

Harsh Pandey

Harsh Pandey

Python Increment - Everything you need to know

Theano Python Beginner Guide for Getting Started

Taygun Dogan

Taygun Dogan

17 min read

Python Classes And Objects

Browse Flexiple's talent pool

Explore our network of top tech talent. Find the perfect match for your dream team.

  • Programmers
  • React Native
  • Ruby on Rails

COMMENTS

  1. Python Assignment jobs

    3,351 Python Assignment jobs available on Indeed.com. Apply to Tutor, Tester, Summer Associate and more!

  2. Python Coding Assignment Jobs, Employment

    478 Python Coding Assignment jobs available on Indeed.com. Apply to Software Engineer, Python Developer, Instructor and more!

  3. 5,432 Remote Python Jobs in June 2024

    Employee Learning & Development Services. Performance Management Services. WordPress Installation & Theme Setup Services. Remarketing Services. Podcast Content Services. See more. Browse 5,432 open jobs and land a remote Python job today. See detailed job requirements, compensation, duration, employer history, & apply today.

  4. Optimizing Job Assignments with Python: A Greedy Approach

    For this, we will utilize Python programming language and the Numpy library for the same. We will also solve a small case on a job assignment. Job assignment involves allocating tasks to workers while minimizing overall completion time or cost. Python's greedy algorithm, combined with NumPy, can solve such problems by iteratively assigning ...

  5. Entry Level Python jobs

    Operations Research Analyst. Air Force Civilian Service 4.4. Valparaiso, FL 32580. $103,409 - $134,435 a year. Full-time. Weekends as needed + 1. 2 yrs experience in computer programming is desired, preferably python. Education requirements: A Degree in operations research; or at least 24 semester hours….

  6. Job Assignment Problem using Branch And Bound

    Solution 1: Brute Force. We generate n! possible job assignments and for each such assignment, we compute its total cost and return the less expensive assignment. Since the solution is a permutation of the n jobs, its complexity is O (n!). Solution 2: Hungarian Algorithm. The optimal assignment can be found using the Hungarian algorithm.

  7. Python assignment jobs

    Online Computer Science assignment help tutor needed in Kanathur Reddykuppam. Python programming, control and data abstraction, file processing, and data visualization. Introduction to computer programming. Assignments solve real data manipulation tasks from science, engineering, business, and the humanities.

  8. Solve Python

    Join over 23 million developers in solving code challenges on HackerRank, one of the best ways to prepare for programming interviews.

  9. Solving an Assignment Problem

    This section presents an example that shows how to solve an assignment problem using both the MIP solver and the CP-SAT solver. Example. In the example there are five workers (numbered 0-4) and four tasks (numbered 0-3).

  10. Python's Assignment Operator: Write Robust Assignments

    Here, variable represents a generic Python variable, while expression represents any Python object that you can provide as a concrete value—also known as a literal—or an expression that evaluates to a value. To execute an assignment statement like the above, Python runs the following steps: Evaluate the right-hand expression to produce a concrete value or object.

  11. Python Coding Assignments on CodeSubmit

    Evaluate for on-the-job skills. Evaluate Python developers with Python-specific coding assessments. ... (and framework) skills, you can rest easy knowing you're making an informed hiring decision. Our assignments are challenging but fun, so your future candidates will appreciate your great hiring process. And for your follow-up interviews, ...

  12. assignment-problem · GitHub Topics · GitHub

    A python program to solve assignment problem by the Kuhn-Munkres algorithm (The Hungarian Method). python tkinter assignment-problem hungarian-algorithm python-gui kuhn-munkres ... Some work I did for an interview for a job as a data scientist optimisation specialist.

  13. ASSIGNMENT PROBLEM (OPERATIONS RESEARCH) USING PYTHON

    However, solving this task for increasing number of jobs and/or resources calls for computational techniques. This article aims at solving an Assignment Problem using the Gurobi package of Python.

  14. Python Assignment Operators

    Python Assignment Operators. Assignment operators are used to assign values to variables: Operator. Example. Same As. Try it. =. x = 5. x = 5.

  15. Assignment Operators in Python

    Assignment Operator. Assignment Operators are used to assign values to variables. This operator is used to assign the value of the right side of the expression to the left side operand. Python. # Assigning values using # Assignment Operator a = 3 b = 5 c = a + b # Output print(c) Output. 8.

  16. Python Exercises, Practice, Challenges

    These free exercises are nothing but Python assignments for the practice where you need to solve different programs and challenges. All exercises are tested on Python 3. Each exercise has 10-20 Questions. The solution is provided for every question. These Python programming exercises are suitable for all Python developers.

  17. Different Forms of Assignment Statements in Python

    Multiple- target assignment: x = y = 75. print(x, y) In this form, Python assigns a reference to the same object (the object which is rightmost) to all the target on the left. OUTPUT. 75 75. 7. Augmented assignment : The augmented assignment is a shorthand assignment that combines an expression and an assignment.

  18. python

    W6 [40, 26, 26] 18, W7 [40, 20, 18] 12] With matrix C being the cost of each worker being assigned to each machine. Matrix I represents the cost of each worker to be idle. I'm currently using scipy.optimize.linear_sum_assignment to determine the minimum cost with a cost matrix. M1 M2 M3. W1 [72, 74, 74,64,M,M,M,M,M,M]

  19. Python

    Python Assignment Operator. The = (equal to) symbol is defined as assignment operator in Python. The value of Python expression on its right is assigned to a single variable on its left. The = symbol as in programming in general (and Python in particular) should not be confused with its usage in Mathematics, where it states that the expressions on the either side of the symbol are equal.

  20. Algorithm for fairly assigning tasks to workers based on skills

    Each task has to be assigned to at least 3 workers, and the workers must match at least one of the tasks' interests: Task 1: Ruby, XML Task 2: XHTML, Python. and so on. So Bob, Fred, or Sam could get Task 1; Susan or Fred could get Task 2. This is all stored in a database thusly: Task. id integer primary key. name varchar.

  21. Solving Assignment Problem using Linear Programming in Python

    From the above results, we can infer that Worker-1 will be assigned to Job-1, Worker-2 will be assigned to job-3, Worker-3 will be assigned to Job-2, and Worker-4 will assign with job-4. Summary. In this article, we have learned about Assignment problems, Problem Formulation, and implementation using the python PuLp library.

  22. Python Practice Problems: Get Ready for Your Next Interview

    For this problem, you'll need to parse a log file with a specified format and generate a report: Log Parser ( logparse.py) Accepts a filename on the command line. The file is a Linux-like log file from a system you are debugging. Mixed in among the various statements are messages indicating the state of the device.

  23. Different Assignment operators in Python

    Assignment operators in Python are in-fix which are used to perform operations on variables or operands and assign values to the operand on the left side of the operator. They perform arithmetic, logical, and bitwise computations. Assignment Operators in Python. Simple assignment operator in Python; Add and equal operator; Subtract and equal ...