• 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.

Simplest way to solve mathematical equations in Python

I want to solve a set of equations, linear, or sometimes quadratic. I don't have a specific problem, but often, I have been in this situation often.

It is simple to use wolframalpha.com , the web equivalent of Mathematica, to solve them. But that doesn't provide the comfort and convenience of an iPython shell.

Is there a simple library to work on linear and quadratic equations from a python shell?

Personally, I find it extremely convenient to use the Casio 991 MS scientific calculator. I know how to set variables, solve equations, and do a lot. I want such a tool preferably usable from within an ipython shell. I am surprised not to have found any. I'm not impressed enough by sage; perhaps I am missing something.

bjb568's user avatar

  • Do you know the Maxima Language and the WxMaxima interface? I find it cozier than IPython –  Foad S. Farimani Commented Nov 24, 2017 at 9:31

16 Answers 16

sympy is exactly what you're looking for.

airstrike's user avatar

  • Upvoted. Let's see a demo! I just posted an answer with a demo of sympy to help get people started in it. –  Gabriel Staples Commented Aug 20, 2022 at 7:26

You discount the best answer as unacceptable.

Your question is "I want a free Computer Algebra System that I can use in Python."

The answer is "SAGE does that."

Have you looked at maxima/macsyma? SAGE provides bindings for it, and that's one of the more powerful free ones.

http://maxima.sourceforge.net/

Paul McMillan's user avatar

Here is how to solve your original question using Python (via Sage). This basically clarifies the remark Paul McMillan makes above.

William Stein's user avatar

For inexact solutions, read up on linear programming and sequential quadratic optimization , then search for Python libraries that performs such optimizations for you.

If the equations require integer solutions, you should search for Diophantine equation solvers for Python.

Just note that using a simple solver for Project Euler is missing the point. The fun, and educational part, is learning how to solve it yourself using primitive methods!

csl's user avatar

  • they can give exact solution - depends on model, constraints & tolerance ... for Continuous Problems - use Gradient Descend Algos... for Mixed Integer Problems see Branch and Bound Method - but it is used in LP Solvers internally and you should not care about algo itself, find libs (scipy.optimize, pulp, GEKKO, Networkx etc depending on task to solve) –  JeeyCi Commented Nov 13, 2023 at 6:42

A free web-service for solving large-scale systems of nonlinear equations (1 million+) is APMonitor.com. There is a browser interface and an API to Python / MATLAB. The API to Python is a single script (apm.py) that is available for download from the apmonitor.com homepage. Once the script is loaded into a Python code, it gives the ability to solve problems of:

  • Nonlinear equations
  • Differential and algebraic equations
  • Least squares model fitting
  • Moving horizon estimation
  • Nonlinear model predictive control

For the new user, the APM Python software has a Google Groups forum where a user can post questions. There are bi-weekly webinars that showcase optimization problems in operations research and engineering.

Below is an example of an optimization problem (hs71.apm).

The optimization problem is solved with the following Python script:

John Hedengren's user avatar

Have you looked at SciPy ?

It has an example in the tutorials on solving linear algebra:

http://docs.scipy.org/doc/scipy/reference/tutorial/linalg.html#solving-linear-system

Andre Miller's user avatar

For reference: Wolfram Alpha's solution :

In python, using sympy's solver module (note that it assumes all equations are set equal to zero):

And of course, a != 1000, as a-1000 is the denominator of the two equations.

Nate's user avatar

I have just started using GNU Scientific Library , which however is C library. Looks like there are Python bindings too. So, it might be worth looking at.

I'd use Octave for this but I agree, the syntax of Octave isn't what I'd call thrilling (and the docs always confuse me more than they help, too).

Aaron Digulla's user avatar

SymPy symbolic Python library demo: symbolically solving math and integrals & pretty-printing the output

From @Autoplectic:

While I have a tendency to write some of the longest answers on Stack Overflow, that is the shortest answer I've seen on Stack Overflow.

Let's add a basic demo.

References and tutorials you'll need:

  • Basic Operations
  • Simplification

Calculus demo I came up with (see here for the main tutorial I looked at to get started):

Short version:

Longer version:

eRCaGuy_hello_world/math/sympy_integral_and_printing.py :

Note that using pprint(integral) is the same as print(pretty(integral)) .

Output of running the above commands:

The SymPy symbolic math library in Python can do pretty much any kind of math, solving equations, simplifying, factoring, substituting values for variables, pretty printing, converting to LaTeX format, etc. etc. It seems to be a pretty robust solver in my very limited use so far. I recommend trying it out.

Installing it, for me (tested on Linux Ubuntu), was as simple as:

Gabriel Staples's user avatar

I don't think there is a unified way of dealing with both linear and quadratic (or generally nonlinear) equations simultaneously. With linear systems, python has bindings to linear algebra and matrix packages. Nonlinear problems tend to be solved on a case by case basis.

Victor Liu's user avatar

  • SAGE's maxima bindings can deal with pretty much anything you throw at them. –  Paul McMillan Commented Oct 29, 2009 at 9:00

It depends on your needs:

If you want an interactive graphical interface, then sage is probably the best solution.

If you want to avoid using a graphical interface, but you still want to do computer algebra, then sympy or maxima may cover your needs. (sympy looks very promising, but it still have a long way to go before they can replace mathematica).

If you don't really need symbolic algrebra, but you need a way to program with matrices, solve differential equations, and minimize functions, then scipy or octave are excelent starting points.

niels's user avatar

Take a look at this:

http://openopt.org/FuncDesignerDoc#Solving_systems_of_nonlinear_equations

It is extremely easy to use and quite powerful

Rossella's user avatar

Well, I just googled into this page by accident. I see many suggestions regarding this and that software tool, but does any tool actually provide an answer? The actual answer is:

[a,b,c] = [200,375,425]

How did I get this? By writing a quick program in the Maxima programming language to find it via "brute force" searching. It only took about 10 minutes to write, seeing as how I'm familiar with the Maxima language. It took a few seconds for the program to run. Here is the program:

euler_solve():= block ( [ a, b, A, B, end:1000],

You can just cut and paste the above code into the wxMaxima user interface, which I run under Ubuntu and not MS Windows. Then you just enter the function name: euler_solve(), hit return, wait a few seconds, and out pops the answer. This particular kind of problem is so simple that you could use any general-purpose programming language to do the search.

R.E.H.'s user avatar

  • 2 [200, 375, 425] is one potential solution, but there's an infinite set of solutions to this set of equations. [-499000, 999, 499001] is another. One numeric solution is probably not what the OP is looking for. –  Nate Commented Mar 16, 2012 at 15:41
  • This answer is not relevant since the question is specific Python. The comment about infinite solutions isn't either since the problem that this question refers to (Project Euler 9) has constraints and specifically limits its solution to a single tuple. –  anddam Commented Jun 4, 2014 at 10:10

Try applying Bisection method in py to find the root given an interval:

Mahmoud's user avatar

On second thoughts, I went through sage in detail and clearly it is the best math free software available.

Just some of the different python math related libraries, it integrates is absolutely awesome.

Mathematics packages contained in Sage:

Other packages contained in Sage:

  • 11 It's impolite to answer your own question with a duplicate of answers provided by others, and then to accept your own answer. Instead, accept someone else's correct answer, and edit your question to include the information you found useful, or reply in a comment. –  Paul McMillan Commented Jan 6, 2011 at 6:57
  • Paul, these points are not the primary driving force of me, nor the site, I think. Get over that obsession. People are here for sharing information. –  lprsd Commented Jan 6, 2011 at 12:25

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 python math numpy scipy equation or ask your own question .

  • The Overflow Blog
  • Navigating cities of code with Norris Numbers
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Feedback requested: How do you use tag hover descriptions for curating and do...

Hot Network Questions

  • Discrete cops and robbers
  • How to create the `c` argument specifiers in Expl3?
  • How do you "stealth" a relativistic superweapon?
  • Is there a way to say "wink wink" or "nudge nudge" in German?
  • Solve an integral analytically
  • What is a transition of point man in French?
  • Is there a law against biohacking your pet?
  • Guitar amplifier placement for live band
  • Enigmatic Puzzle 4: Three Leaf Clover
  • What is the origin and meaning of the phrase “wear the brown helmet”?
  • How to cite a book if only its chapters have DOIs?
  • Are all simple groups of order coprime to 3 cyclic? If so, why?
  • Did I write the locks properly to prevent concurrency issues?
  • Unreachable statement wen upgrading APEX class version
  • Venus’ LIP period starts today, can we save the Venusians?
  • Sci-fi book about humanity warring against aliens that eliminate all species in the galaxy
  • Were there mistakes in converting Dijkstra's Algol-60 compiler to Pascal?
  • Is It Possible to Assign Meaningful Amplitudes to Properties in Quantum Mechanics?
  • Power line crossing data lines via the ground plane
  • Unexpected behaviour during implicit conversion in C
  • Does a Way of the Astral Self Monk HAVE to do force damage with Arms of the Astral Self from 10' away, or can it be bludgeoning?
  • Do temperature variations make trains on Mars impractical?
  • conflict of \counterwithin and cleveref package when sectioncounter is reset
  • A man hires someone to murders his wife, but she kills the attacker in self-defense. What crime has the husband committed?

mathematical problem solving using python coursera

  • Docs »
  • Introduction
  • Edit on GitHub
Nothing in the world takes place without optimization, and there is no doubt that all aspects of the world that have a rational basis can be explained by optimization methods. Leonhard Euler, 1744 (translation found in “Optimization Stories”, edited by Martin Grötschel).

Introduction ¶

This introductory chapter is a run-up to Chapter 2 onwards. It is an overview of mathematical optimization through some simple examples, presenting also the main characteristics of the solver used in this book: SCIP ( http://scip.zib.de ).

The rest of this chapter is organized as follows. Section Mathematical Optimization introduces the basics of mathematical optimization and illustrates main ideas via a simple example. Section Linear Optimization presents a real-world production problem to discuss concepts and definitions of linear-optimization model, showing details of SCIP/Python code for solving a production problem. Section Integer Optimization introduces an integer optimization model by adding integer conditions to variables, taking as an example a simple puzzle sometimes used in junior high school examinations. A simple transportation problem, which is a special form of the linear optimization problem, along with its solution is discussed in Section Transportation Problem . Here we show how to model an optimization problem as a function, using SCIP/Python. Section Duality explains duality, an important theoretical background of linear optimization, by taking a transportation problem as an example. Section Multi-product Transportation Problem presents a multi-commodity transportation problem, which is an generalization of the transportation, and describes how to handle sparse data with SCIP/Python. Section Blending problem introduces mixture problems as an application example of linear optimization. Section Fraction optimization problem presents the fraction optimization problem, showing two ways to reduce it to a linear problem. Section Multi-Constrained Knapsack Problem illustrates a knapsack problem with details of its solution procedure, including an explanation on how to debug a formulation. Section The Modern Diet Problem considers how to cope with nutritional problems, showing an example of an optimization problem with no solution.

Mathematical Optimization ¶

Let us start by describing what mathematical optimization is: it is the science of finding the “best” solution based on a given objective function, i.e., finding a solution which is at least as good and any other possible solution. In order to do this, we must start by describing the actual problem in terms of mathematical formulas; then, we will need a methodology to obtain an optimal solution from these formulas. Usually, these formulas consist of constraints, describing conditions that must be satisfied, and by an objective function.

  • objective function (which we want to maximize of minimize);
  • conditions of the problem: constraint 1, constraint 2, …
  • a set of variables : the unknowns that need to be found as a solution to the problem;
  • a set of constraints : equations or inequalities that represent requirements in the problem as relationships between the variables
  • an objective function : an expression, in terms of the defined variables, which determines e.g. the total cost, or the profit of the targeted problem.

The problem is a minimization when smaller values of the objective are preferrable, as with costs; it is a maximization when larger values are better, as with profits. The essence of the problem is the same, whether it is a minimization or a maximization (one can be converted into the other simply by putting a minus sign in the objective function).

In this text, the problem is described by the following format.

Maximize or minimize Objective function Subject to: Constraint 1 Constraint 2 …

The optimization problem seeks a solution to either minimize or maximize the objective function, while satisfying all the constraints. Such a desirable solution is called optimum or optimal solution — the best possible from all candidate solutions measured by the value of the objective function. The variables in the model are typically defined to be non-negative real numbers.

There are many kinds of mathematical optimization problems; the most basic and simple is linear optimization [1] . In a linear optimization problem, the objective function and the constraints are all linear expressions (which are straight lines, when represented graphically). If our variables are \(x_1, x_2, \ldots, x_n\) , a linear expression has the form \(a_1 x_1 + a_2 x_2 + \ldots + ax_n\) , where \(a_1, \ldots, a_n\) are constants.

For example,

is a linear optimization problem.

One of the important features of linear optimization problems is that they are easy to solve. Common texts on mathematical optimization describe in lengthy detail how a linear optimization problem can be solved. Taking the extreme case, for most practitioners, how to solve a linear optimization problem is not important. For details on how methods for solving these problems have emerged, see Margin seminar 1 . Most of the software packages for mathematical optimization support linear optimization. Given a description of the problem, an optimum solution (i.e., a solution that is guaranteed to be the best answer) to most of the practical problems can be obtained in an extremely short time.

Unfortunately, not all the problems that we find in the real world can be described as a linear optimization problem. Simple linear expressions are not enough to accurately represent many complex conditions that occur in practice. In general, optimization problems that do not fit in the linear optimization paradigm are called nonlinear optimization problems.

In practice, nonlinear optimization problems are often difficult to solve in a reliable manner. Using the mathematical optimization solver covered in this document, SCIP, it is possible to efficiently handle some nonlinear functions; in particular, quadratic optimization (involving functions which are a polynomial of up to two, such as \(x^2 + xy\) ) is well supported, especially if they are convex.

A different complication arises when some of the variables must take on integer values; in this situation, even if the expressions in the model are linear, the general case belongs to a class of difficult problems (technically, the NP-hard class [2] ). Such problems are called integer optimization problems; with ingenuity, it is possible to model a variety of practical situations under this paradigm. The case where some of the variables are restricted to integer values, and other are continuous, is called a mixed-integer optimization problem. Even for solvers that do not support nonlinear optimization, some techniques allow us to use mixed-integer optimization to approximate arbitrary nonlinear functions; these techniques (piecewise linear approximation) are described in detail in Chapter Piecewise linear approximation of nonlinear functions .

Linear Optimization ¶

We begin with a simple linear optimization problem; the goal is to explain the terminology commonly used optimization.

Let us start by explaining the meaning of \(x_1, x_2, x_3\) : these are values that we do not know, and which can change continuously; hence, they are called variables .

The first expression defines the function to be maximized, which is called the objective function .

The second and subsequent expressions restrict the value of the variables \(x1, x2, x3\) , and are commonly referred to as constraints . Expressions ensuring that the variables are non-negative \((x1, x2, x3 \geq 0)\) have the specific name of sign restrictions or non-negativity constraints . As these variables can take any non-negative real number, they are called real variables , or continuous variables .

In this problem, both the objective function and the constraint expressions consist of adding and subtracting the variables \(x_1, x_2, x_3\) multiplied by a constant. These are called linear expressions . The problem of maximizing (or minimizing) a linear objective function subject to linear constraints is called a linear optimization problem .

The set of values for variables \(x_1, x_2, x_3\) is called a solution , and if it satisfies all constraints it is called a feasible solution . Among feasible solutions, those that maximize (or minimize) the objective function are called optimal solutions . The maximum (or minimum) value of the objective function is called the optimum . In general, there are multiple solutions with an optimum objective value, but usually the aim is to find just one of them.

Finding such point can be explored in some methodical way; this is what a linear optimization solver does for finding the optimum. Without delay, we are going to see how to solve this example using the SCIP solver. SCIP has been developed at the Zuse Institute Berlin (ZIB), an interdisciplinary research institute for applied mathematics and computing. SCIP solver can be called from several programming languages; for this book we have chosen the very high-level language Python . For more information about SCIP and Python, see appendices SCIPintro and PYTHONintro , respectively.

The first thing to do is to read definitions contained in the SCIP module (a module is a different file containing programs written in Python). The SCIP module is called pyscipopt , and functionality defined there can be accessed with:

The instruction for using a module is import . In this statement we are importing the definitions of Model . We could also have used from pyscipopt import * , where the asterisk means to import all the definitions available in pyscipopt . .. ; we have imported just some of them, and we could have used other idioms, as we will see later. One of the features of Python is that, if the appropriate module is loaded, a program can do virtually anything [3] .

The next operation is to create an optimization model; this can be done with the Model class, which we have imported from the pyscipopt module.

With this instruction, we create an object named model , belonging the class Model (more precisely, model is a reference to that object). The model description is the (optional) string "Simple linear optimization" , passed as an argument.

There is a number of actions that can be done with objects of type Model , allowing us to add variables and constraints to the model before solving it. We start defining variables \(x_1, x_2, x_3\) (in the program, x1, x2, x3 ). We can generate a variable using the method addVar of the model object created above (a method is a function associated with objects of a class). For example, to generate a variable x1 we use the following statement:

With this statement, the method addVar of class Model is called, creating a variable x1 (to be precise, x1 holds a reference to the variable object). In Python, arguments are values passed to a function or method when calling it (each argument corresponds to a parameter that has been specified in the function definition). Arguments to this method are specified within parenthesis after addVar . There are several ways to specify arguments in Python, but the clearest way is to write argument name = argument value as a keyword argument .

Here, vtype = "C" indicates that this is a continuous variable, and name = "x1" indicates that its name (used, e.g., for printing) is the string "x1" . The complete signature (i.e., the set of parameters) for the addVar method is the following:

Arguments are, in order, the name, the type of variable, the lower bound, the upper bound, the coefficients in the objective function. The last parameter, pricedVar is used for column generation , a method that will be explained in Chapter Bin packing and cutting stock problems . In Python, when calling a method omitting keyword arguments (which are optional) default values (given after = ) are applied. In the case of addVar , all the parameters are optional. This means that if we add a variable with model.addVar() , SCIP will create a continuous, non-negative and unbounded variable, whose name is an empty string, with coefficient 0 in the objective ( obj=0 ). The default value for the lower bound is specified with lb=0.0 , and the upper bound ub is implicitly assigned the value infinity (in Python, the constant None usually means the absence of a value). When calling a function or method, keyword arguments without a default value cannot be omitted.

Functions and methods may also be called by writing the arguments without their name, in a predetermined order, as in:

Other variables may be generated similarly. Note that the third constraint \(x 3 \leq 30\) is the upper bound constraint of variable \(x_3\) , so we may write ub = 30 when declaring the variable.

Next, we will see how to enter a constraint. For specifying a constraint, we will need to create a linear expression , i.e., an expression in the form of \(c_1 x_1 + c_2 x2 + \ldots + c_n x_n\) , where each \(c_i\) is a constant and each \(x_i\) is a variable. We can specify a linear constraint through a relation between two linear expressions. In SCIP’s Python interface, the constraint \(2x1 + x2 + x3 \leq 60\) is entered by using method addConstr as follows:

The signature for addConstr (ignoring some parameters which are not of interest now) is:

SCIP supports more general cases, but for the time being let us concentrate on linear constraints. In this case, parameter relation is a linear constraint, including a left-hand side (lhs), a right-hand side (rhs), and the sense of the constraint. Both lhs and rhs may be constants, variables, or linear expressions; sense maybe "<=" for less than or equal to, ">=" for greater than or equal to, or "==" for equality. The name of the constraint is optional, the default being an empty string. Linear constraints may be specified in several ways; for example, the previous constraint could be written equivalently as:

Before solving the model, we must specify the objective using the setObjective method, as in:

The signature for setObjective is:

The first argument of setObjective is a linear (or more general) expression, and the second argument specifies the direction of the objective function with strings "minimize" (the default) or "maximize" . (The third parameter, clear , if "true" indicates that coefficients for all other variables should be set to zero.) We may also set the direction of optimization using model.setMinimize() or model.setMaximize() .

At this point, we can solve the problem using the method optimize of the model object:

After executing this statement — if the problem is feasible and bounded, thus allowing completion of the solution process —, we can output the optimal value of each variable. This can be done through method getVal of Model objects; e.g.:

The complete program for solving our model can be stated as follows:

from pyscipopt import Model model = Model("Simple linear optimization") x1 = model.addVar(vtype="C", name="x1") x2 = model.addVar(vtype="C", name="x2") x3 = model.addVar(vtype="C", name="x3") model.addCons(2*x1 + x2 + x3 <= 60) model.addCons(x1 + 2*x2 + x3 <= 60) model.addCons(x3 <= 30) model.setObjective(15*x1 + 18*x2 + 30*x3, "maximize") model.optimize() if model.getStatus() == "optimal": print("Optimal value:", model.getObjVal()) print("Solution:") print(" x1 = ", model.getVal(x1)) print(" x2 = ", model.getVal(x2)) print(" x3 = ", model.getVal(x3)) else: print("Problem could not be solved to optimality")

If we execute this Python program, the output will be:

[solver progress output omitted] Optimal value: 1230.0 Solution: x1 = 10.0 x2 = 10.0 x3 = 30.0

The first lines, not shown, report progress of the SCIP solver (this can be suppressed) while lines 2 to 6 correspond to the output instructions of lines 14 to 16 of the previous program.

Margin seminar 1

Linear programming

Linear programming was proposed by George Dantzig in 1947, based on the work of three Nobel laureate economists: Wassily Leontief, Leonid Kantrovich, Tjalling Koopmans. At that time, the term used was “optimization in linear structure”, but it was renamed as “linear programming” in 1948, and this is the name commonly used afterwards. The simplex method developed by Dantzig has long been the almost unique algorithm for linear optimization problems, but it was pointed out that there are (mostly theoretical) cases where the method requires a very long time.

The question as to whether linear optimization problems can be solved efficiently in the theoretical sense (in other words, whether there is an algorithm which solves linear optimization problems in polynomial time) has been answered when the ellipsoid method was proposed by Leonid Khachiyan (Khachian), of the former Soviet Union, in 1979. Nevertheless, the algorithm of Khachiyan was only theoretical, and in practice the supremacy of the simplex method was unshaken. However, the interior point method proposed by Narendra Karmarkar in 1984 [4] has been proved to be theoretically efficient, and in practice it was found that its performance can be similar or higher than the simplex method’s. Currently available optimization solvers are usually equipped with both the simplex method (and its dual version, the dual simplex method ) and with interior point methods, and are designed so that users can choose the most appropriate of them.

Integer Optimization ¶

For many real-world optimization problems, sometimes it is necessary to obtain solutions composed of integers instead of real numbers. For instance, there are many puzzles like this: “In a farm having chicken and rabbits, there are 5 heads and 16 feet. How many chicken and rabbits are there?” Answer to this puzzle is meaningful if the solution has integer values only.

Let us consider a concrete puzzle.

Let us formalize this as an optimization problem with mathematical formulas. This process of describing a situation algebraically is called the formulation of a problem in mathematical optimization.

Then, the number of heads can be expressed as \(x + y + z\) . Cranes have two legs each, turtles have four legs each, and each octopus has eight legs. Therefore, the number of legs can be expressed as \(2x + 4y + 8z\) . So the set of \(x, y, z\) must satisfy the following “constraints”:

Since there are three variables and only two equations, there may be more than one solution. Therefore, we add a condition to minimize the sum \(y + z\) of the number of turtles and octopuses. This is the “objective function”. We obtain the complete model after adding the non-negativity constraints.

When we use a linear optimization solver, we obtain the solution \(x = 29.3333, y = 0, z = 2.66667\) . This is obviously a strange answer. Cranes, tortoises and octopuses can be divided when they are lined up as food on the shelves, but not when they are alive. To solve this model, we need to add conditions to force the variables to have integer values. These are called integrality constraints : \(x, y, z\) must be non-negative integers. Linear optimization problems with conditions requiring variables to be integers are called integer optimization problems . For the puzzle we are solving, thus, the correct model is:

Below is a simple Python/SCIP program for solving it. The main difference with respect to the programs that we have seen before concerns the declaration of variables; in this case, there is an argument to addVar for specifying that variables are integer: vtype="I" . Continuous variables (the default) can be explicitly declared with vtype="C" , and binary variables — a special case of integers, restricted to the values 0 or 1 — are declared with vtype="B" .

from pyscipopt import Model model = Model("Simple linear optimization") x = model.addVar(vtype="I", name="x") y = model.addVar(vtype="I", name="y") z = model.addVar(vtype="I", name="x") model.addCons(x + y + z == 32,"Heads") model.addCons(2*x + 4*y + 8*z == 80,"Legs") model.setObjective(y + z, "minimize") model.optimize() if model.getStatus() == "optimal": print("Optimal value:", model.getObjVal()) print("Solution:") print(" x = ", model.getVal(x)) print(" y = ", model.getVal(y)) print(" z = ", model.getVal(z)) else: print("Problem could not be solved to optimality")

For small integer optimization problems like this, the answer can be quickly found: \(x=28\) , \(y=2\) , and \(z=2\) , meaning that there are 28 cranes, 2 turtles and 2 octopuses. Notice that this solution is completely different of the continuous version’s; in general, we cannot guess the value of an integer solution from the continuous model. In general, integer-optimization problems are much harder to solve when compared to linear-optimization problems.

[ source code ]

Transportation Problem ¶

The next example is a classical linear optimization problem called the transportation problem . Consider the following scenario.

_images/transK.png

Transportation problem

Data for the transportation problem
    Customers \(i\)  
Transportation cost \(c_{ij}\)   1 2 3 4 5 capacity \(M_j\)
plant \(j\) 1 4 5 6 8 10 500
2 6 4 3 5 8 500
3 9 7 4 2 4 500
demand \(d_i\)   80 270 250 160 180  

Table Data for the transportation problem shows customer demand volumes, shipping costs from each factory to each customer, and production capacity at each factory. More precisely, \(d_i\) is the demand of customer \(i\) , where \(i =\) 1 to 5. Each plant \(j\) can supply its customers with goods but their production capacities are limited by \(M_j\) , where \(j =\) 1 to 3. Transportation cost for shipping goods from plant \(i\) to customer \(j\) is given in the table by \(c_{ij}\) .

Let us formulate the above problem as a linear optimization model. Suppose that the number of customers is \(n\) and the number of factories is \(m\) . Each customer is represented by \(i = 1, 2, \ldots, n\) , and each factory by \(j = 1, 2, \ldots, m\) . Also, let the set of customers be \(I = {1, 2, \ldots, n}\) and the set of factories \(J = {1, 2, \ldots, m}\) . Suppose that the demand amount of customer \(i\) is \(d_i\) , the transportation cost for shipping one unit of demand from plant \(i\) to customer \(j\) is \(c_{ij}\) , and that each plant \(j\) can supply its customers with goods, but their production capacities are limited by \(M_j\)

We use continuous variables as defined below.

Using the above symbols and variables, the transport problem can be formulated as the following linear optimization problem.

The objective function is the minimization of the sum of transportation costs. The first constraint requires that the demand is satisfied, and the second constraint ensures that factory capacities are not exceeded.

Let us solve this with Python/SCIP. First, we prepare the data needed for describing an instance [5] . In the transportation problem, it is necessary to prepare data defining demand amount \(d_i\) , transportation costs \(c_{ij}\) , capacities \(M_j\) . In the following program, we will use the same symbol used in the formulation for holding a Python’s dictionary. A dictionary is composed of a key and a value as its mapping, and is generated by arranging pais of keys and values in brackets, separated by commas: {key1:value1, key2:value2, ...} . (For details on dictionaries see appendix A.2.5 ).

The demand amount \(d_i\) is stored in a dictionary d with the customer’s number as the key and the demand amount as the value, and the capacity \(M_j\) is stored in the dictionary M with the factory number as the key and the capacity as the value.

In addition, a list I of customers’ numbers and a list J of factory numbers can be prepared as follows.

Actually, the dictionaries and lists above can be created at once by using the multidict function available in Python/SCIP, as follows.

When the dictionary is entered as an argument, the multidict function returns a pair of values; the first is the list of keys, and the second value is the dictionary sent as argument. Later, we will see that this function is very useful when we want to associate more than one value to each key. (For a more detailed usage of multidict , see appendix B.4 .)

Shipping cost \(c_{ij}\) has two subscripts. This is represented in Python by a dictionary c with a tuple of subscripts (customer and factory) as keys, and the corresponding costs as values. A tuple is a sequence, like a list; however, unlike a list, its contents can not be changed: a tuple is immutable . Tuples are created using parentheses and, due to the fact that they are immutable, can be used as keys of a dictionary (see appendix A.2.4 for details on tuples).

With this dictionary c , the transportation cost from factory \(j\) to customer \(i\) can be accessed with c[(i,j)] or c[i,j] (in a tuple, we can omit parenthesis).

As a programming habit, it is preferable not to use a one-letter variables such as d, M, c above. We have done it so that the same symbols are used in the formulation and in the program. However, in larger programs it is recommended to use meaningful variables names, such as demand, capacity, cost .

Let us write a program to solve the instance specified above.

model = Model("transportation") x = {} for i in I: for j in J: x[i,j] = model.addVar(vtype="C", name="x(%s,%s)" % (i,j))

First, we define a Python variable x , which initially contains an empty dictionary (line 2). We then use dictionary x to store variable’s objects, each of them corresponding to an \(x_{ij}\) of our model (lines 3 to 5).  As I is a list of customers’ indices, the for cycle of line 3 iterates over all customers \(i\) . Likewise, since J is a list of factory indices, the for cycle of line 4 iterates over the quantity transported from factory \(j\) to customer \(i\) (see appendix A.4.2 for more information about iteration). In the rightmost part of line 5 the variable is named x(i,j) ; this uses Python’s string format operation % , where %s represents substitution into a character string.

Next we add constraints. First, we add the constraint

which imposes that the demand is satisfied. Since this is a constraint for all customers \(i\) , a constraint \(\sum_{j=1}^m x_{ij} = d_i\) is added by the addCons method (line 2) at each iteration of the for cycle of line 1.

for i in I: model.addCons(quicksum(x[i,j] for j in J if (i,j) in x) == d[i], name="Demand(%s)" % i)

Notice that here we also give a name, Demand(i) , to constraints. Although, as for variables, the name of a constraint may be omitted, it is desirable to add an appropriate name for later reference (an example of this will be seen in Duality ). The quicksum function on the second line is an enhanced version of the sum function available in Python, used in Python/SCIP to do the computation of linear expressions more efficiently. It is possible to provide quicksum explicitly with a list, or with a list generated by iteration with a for statement, as we did here; these generator work in the same way as in list comprehensions in Python (see appendix A.4.2 ). In the above example, we calculate a linear expression by summing variables \(x_{ij}\) for element \(j \in J\) by means of quicksum(x[i,j] for j in J) . (For a more detailed explanation of quicksum , see appendix B.4 .)

Similarly, we add the factory capacity constraint

to the model as follows:

for j in J: model.addCons(quicksum(x[i,j] for i in I if (i,j) in x) <= M[j], name="Capacity(%s)" % j)

Again, we give a name Capacity(j) to each constraint. In the following, to simplify the description, names of constraints are often omitted; but in fact it is safer to give an appropriate name.

The objective function

is set using the setObjective method, as follows.

model.setObjective(quicksum(c[i,j]*x[i,j] for (i,j) in x), "minimize")

Finally, we can optimize the model and display the result.

model.optimize() print("Optimal value:", model.getObjVal()) EPS = 1.e-6 for (i,j) in x: if model.getVal(x[i,j]) > EPS: print("sending quantity %10s from factory %3s to customer %3s" % (model.getVal(x[i,j]),j,i))

In this code, for (i,j) in x in line 4 is an iteration over dictionary x , holding our model’s variable. This iteration goes through all the tuples \((i,j)\) of customers and factories which are keys of the dictionary. Line 5 is a conditional statement for outputting only non-zero variables. Line 6 uses Python’s string formatting operator % , where %10s is converted into a 10-digit character string and %3s is converted into a 3-digit character string.

When the above program is executed, the following result is obtained. The results are shown in Table Optimal solution for the transportation problem and Figure Transportation problem .

[solver progress output omitted] SCIP Status : problem is solved [optimal solution found] Solving Time (sec) : 0.00 Solving Nodes : 1 Primal Bound : +3.35000000000000e+03 (1 solutions) Dual Bound : +3.35000000000000e+03 Gap : 0.00 % Optimal value: 3350.0 sending quantity 230.0 from factory 2 to customer 3 sending quantity 20.0 from factory 3 to customer 3 sending quantity 160.0 from factory 3 to customer 4 sending quantity 270.0 from factory 2 to customer 2 sending quantity 80.0 from factory 1 to customer 1 sending quantity 180.0 from factory 3 to customer 5
Optimal solution for the transportation problem
Customer \(i\) 1 2 3 4 5    
Amount demanded 80 270 250 160 180    
Plant \(j\) Optimum volume transported total capacity
1 80         80 500
2   270 230     500 500
3     20 160 180 360 500

Consider the following scenario.

In order to solve this problem smartly, the concept of dual problem is useful. Here, the dual problem is a linear optimization problem associated to the original problem (which in this context is called the primal problem). The derivation method and meaning of the dual problem are given in Margin seminar 2 ; here, we will explain how to use information from the dual of the transportation problem with Python/SCIP.

In order to investigate whether or not a factory can be expanded, let us first focus on the capacity constraint

For such an inequality constraint, a variable representing the difference between the right and the left hand sides, \(M_j - \sum_{i \in I} x_{ij}\) , is called a slack variable . Of course, one can easily calculate slack variables from the optimal solution, but in Python/SCIP we can look at the getSlack attribute for constraint objects. Also, the optimal dual variable for a constraint can be obtained with the getDualsolLinear attribute. This represents the amount of reduction on costs when increasing the capacity constraint by one unit (see Margin seminar 2 ).

In order to estimate the cost of additional orders from customers, we focus on the demand satisfaction constraint

Since this is an equality constraint, all slack variables are 0. The optimal value of the dual variable associated with this constraint represents the increase in costs as demand increases by one unit.

Margin seminar 2

Duality in linear programming provides a unifying theory that develops the relationships between a given linear program and another related linear program, stated in terms of variables with this shadow-price interpretation. The importance of duality is twofold. First, fully understanding the shadow-price interpretation of the optimal simplex multipliers can prove very useful in understanding the implications of a particular linear-programming model. Second, it is often possible to solve the related linear program with the shadow prices as the variables in place of, or in conjunction with, the original linear program, thereby taking advantage of some computational efficiencies. The importance of duality for computational procedures will become more apparent in later chapters on network-flow problems and large-scale systems.

Let us re-visit the wine production problem considered earlier to discuss some important concepts in linear-optimization models that play vital role in sensitivity analysis . Sensitivity analysis is important for finding out how optimal solution and optimal value may change when there is any change to the data used in the model. Since data may not always be considered as totally accurate, such analysis can be very helpful to the decision makers.

Let us assume that an entrepreneur is interested in the wine making company and would like to buy its resources. The entrepreneur then needs to find out how much to pay for each unit of each of the resources, the pure-grape wines of 2010 A, B and C. This can be done by solving the dual version of the model that we will discuss next.

Let \(y_1 , y_2\) and \(y_3\) be the price paid, per barrel of Alfrocheiro, Baga, and Castelão, respectively. Then, the total price that should be paid is the quantities of each of the wines in inventory times their prices, i.e., \(60y_1 + 60y_2 + 30y_3\) . Since the entrepreneur would like the purchasing cost to be minimum, this is the objective function for minimization. Now, for each of the resources, constraints in the model must ensure that prices are high enough for the company to sell to the entrepreneur. For instance, with two barrels of A and one barrel of B, the company can prepare blend \(D\) worth 15; hence, it must be offered \(2y_1 + y_2 \ge 15\) . Similarly we obtain \(y_1 + 2y_2 \ge 18\) and \(y_1 + y_2 + y_3 \ge 30\) for the blends M and S, respectively. Thus we can formulate a dual model, stated as follows (for a more sound derivation, using Lagrange multipliers, see lagrange ).

The variables used in the linear-optimization model of the production problem are called primal variables and their solution values directly solve the optimization problem. The linear-optimization model in this setting is called the primal model .

As seen above, associated with every primal model, there is a dual model. The relationships between primal and dual problems can provide significant information regarding the quality of solutions found and sensitivity of the coefficients used. Moreover, they also provide vital economic interpretations. For example, \(y_1\) , the price paid for one unit of Alfrocheiro pure-grape wine is called the shadow price of that resource, because it is the amount by which the optimal value of the primal model will change for a unit increase in its availability — or, equivalently, the price the company would be willing to pay for an additional unit of that resource.

Gurobi allows us to access the shadow prices (i.e., the optimal values of the dual variables associated with each constraint) by means of the .Pi attribute of the constraint class; e.g., in the model for the wine production company of program wblending we are printing these values in line 31.

Another concept important in duality is the reduced cost , which is associated with each decision variable. It is defined as the change in objective function value if one unit of some product that is normally not produced is forced into production; it can also be seen as the amount that the coefficient in the objective has to improve, for a variable that is zero in the optimal solution to become non-zero. Therefore, reduced cost is also appropriately called opportunity cost . Shadow prices and reduced costs allow sensitivity analysis in linear-optimization and help determine how sensitive the solutions are to small changes in the data. Such analysis can tell us how the solution will change if the objective function coefficients change or if the resource availability changes. It can also tell us how the solution may change if a new constraint is brought into the model. Gurobi allows us accessing the reduced costs through the .RC attribute of the variable class; e.g., x.RC is the reduced cost of variable x in the optimal solution.

As we will see later, primal and dual models can be effectively used not only to gain insights into the solution but also to find a bound for the linear-optimization relaxation of an integer-optimization model; linear-optimization relaxation is obtained by having the integrality constraints relaxed to non-integer solution values. Typically, an integer-optimization model is much harder to solve than its linear-optimization relaxation. Specialized algorithms have been designed around the relaxation versions of primal as well as dual optimization models for finding optimal solution more efficiently. Optimal solution of a relaxation model gives a bound for the optimal solution value of the underlying integer-optimization model, and that can be exploited in a branch-and-bound scheme for solving the integer optimization model.

Multi-product Transportation Problem ¶

In the previous transportation problem, we considered only one kind of goods produced at the production plants. In the real-world, however, that is a very restrictive scenario: A producer typically produces many different kinds of products and the customers typically demand different sets of the products available from the producers. Moreover, some producers may be specialized into producing only certain kinds of products while some others may only supply to certain customers. Therefore, a general instance of the transportation problem needs to be less restrictive and account for many such possibilities.

_images/mctranspK.png

Multicommodity transportation

A more general version of the transportation problem is typically studied as a multi-commodity transportation model. A linear-optimization model can be built using decision variables \(x_{ijk}\) where \(i\) denotes the customer, \(j\) denotes the production plant and \(k\) denotes the product type. Customer demand is indexed by \(i\) and \(k\) to denote the customer and product type. Then the model can be stated as follows.

Note that the objective function addresses the minimum total cost for all possible cost combinations involving customers, production plants and product types. The first set of constraints ensure that all demands of the product types from the customers are met exactly while the second set of constraints ensure that capacity at each production plant is not exceeded by taking into account all product types and all customers.

A model for this in Python/Gurobi can be written as follows:

def mctransp(I, J, K, c, d, M): model = Model("multi-commodity transportation") x = {} for i,j,k in c: x[i,j,k] = model.addVar(vtype="C", name="x[%s,%s,%s]" % (i, j, k)) model.update() for i in I: for k in K: model.addConstr(quicksum(x[i,j,k] for j in J if (i,j,k) in x) == d[i,k], "Demand[%s,%s]" % (i,k)) for j in J: model.addConstr(quicksum(x[i,j,k] for (i,j2,k) in x if j2 == j) <= M[j], "Capacity[%s]" % j) model.setObjective(quicksum(c[i,j,k]*x[i,j,k] for i,j,k in x), GRB.MINIMIZE) model.update() model.__data = x return model

Variables are created in line 5. In lines 9 and 10 we create a list the variables that appear in each demand-satisfaction constraint, and the corresponding coefficients; these are then used for creating a linear expression, which is used as the left-hand side of a constraint in line 11. Capacity constraints are created in a similar way, in lines 13 to 15. For an example, consider now the same three production plants and five customers as before. Plant 1 produces two products, football and volleyball; it can supply football only to Customer 1 and volleyball to all five customers. Plant 2 produces football and basketball; it can supply football to Customers 2 and 3, basketball to Customers 1, 2 and 3. Plant 3 produces football, basketball and rugby ball; it can supply football and basketball to Customers 4 and 5, rugby ball to all five customers.

Let us specify the data for this problem in a Python program. First of all, we must state what products each of the plants can manufacture; on dictionary produce the key is the plant, to which we are associating a list of compatible products. We also create a dictionary M with the capacity of each plant (3000 units, in this instance).

The demand for each of the customers can be written as a double dictionary: for each customer, we associate a dictionary of products and quantities demanded.

For determining the transportation cost, we may specify the unit weight for each product and the transportation cost per unit of weight; then, we calculate \(c_{ijk}\) as their product:

We are now ready to construct a model using this data, and solving it:

If we execute this Python program, the output is the following:

Optimize a model with 18 rows, 40 columns and 70 nonzeros Presolve removed 18 rows and 40 columns Presolve time: 0.00s Presolve: All rows and columns removed Iteration Objective Primal Inf. Dual Inf. Time 0 1.7400000e+04 0.000000e+00 0.000000e+00 0s Solved in 0 iterations and 0.00 seconds Optimal objective 1.740000000e+04 Optimal value: 17400.0 sending 100.0 units of 2 from plant 3 to customer 4 sending 210.0 units of 3 from plant 3 to customer 3 sending 40.0 units of 3 from plant 2 to customer 3 sending 40.0 units of 1 from plant 2 to customer 1 sending 10.0 units of 3 from plant 2 to customer 1 sending 100.0 units of 2 from plant 1 to customer 2 sending 100.0 units of 3 from plant 2 to customer 2 sending 70.0 units of 1 from plant 2 to customer 2 sending 60.0 units of 1 from plant 2 to customer 4 sending 30.0 units of 2 from plant 1 to customer 1 sending 180.0 units of 1 from plant 2 to customer 5

Readers may have noticed by now that for these two transportation problems, even though we have used linear-optimization models to solve them, the optimal solutions are integer-valued — as if we have solved integer-optimization models instead. This is because of the special structures of the constraints in the transportation problems that allow this property, commonly referred to as unimodularity . This property has enormous significance because, for many integer-optimization problems that can be modeled as transportation problems, we only need to solve their linear-optimization relaxations.

Blending problem ¶

Fraction optimization problem ¶, multi-constrained knapsack problem ¶.

Knapsack problems are specially structured optimization problems. The general notion of the knapsack problem is to fill up a knapsack of certain capacity with items from a given set such that the collection has maximum value with respect to some special attribute of the items. For instance, given a knapsack of certain volume and several items of different weights, the problem can be that of taking the heaviest collection of the items in the knapsack. Based on weights, the knapsack can then be appropriately filled by a collection that is optimal in the context of weight as the special attribute.

Suppose we have a knapsack of volume 10,000 cubic-cm that can carry up to 7 Kg weight. We have four items having weights 2, 3, 4 and 5, respectively, and volume 3000, 3500, 5100 and 7200, respectively. Associated with each of the items is its value of 16, 19, 23 and 28, respectively. We would like to fill the knapsack with items such that the total value is maximum.

FIGS/knapsack.png

Knapsack instance

An integer-optimization model of this problem can be found by defining the decision variables \(x_j=\) 1 if item \(j\) is taken, and \(x_j = 0\) otherwise, where \(j =\) 1 to 4. For constraints, we need to make sure that total weight does not exceed 7 kg and total volume does not exceed 10,000 cubic-cm. Thus, we have an integer-optimization model:

The standard version of the knapsack problem concerns the maximization of the profit subject to a constraint limiting the weight allowed in the knapsack to a constant \(W\) ; the objective is to \(\mbox{maximize } \sum_j {v_j x_j}\) subject to \(\sum_j {w_j x_j \leq W}\) , with \(x_j \in \{0,1\}\) , where \(v_j\) is the value of item \(j\) and \(w_j\) is its weight. A more general problem includes constraints in more than one dimension, say, \(m\) dimensions (as in the example above); this is called the multi-constrained knapsack problem, or \(m\) -dimensional knapsack problem. If we denote the “weight” of an object \(j\) in dimension \(i\) by \(a_{ij}\) and the capacity of the knapsack in this dimension by \(b_i\) , an integer-optimization model of this problem has the following structure:

A Python/Gurobi model for the multi-constrained knapsack problem is:

def mkp(I, J, v, a, b): model = Model("mkp") x = {} for j in J: x[j] = model.addVar(vtype="B", name="x[%d]"%j) model.update() for i in I: model.addConstr(quicksum(a[i,j]*x[j] for j in J) <= b[i], "Dimension[%d]"%i) model.setObjective(quicksum(v[j]*x[j] for j in J), GRB.MAXIMIZE) model.update() return model

This model can be used to solve the example above in the following way:

J,v = multidict({1:16, 2:19, 3:23, 4:28}) a = {(1,1):2, (1,2):3, (1,3):4, (1,4):5, (2,1):3000, (2,2):3500, (2,3):5100, (2,4):7200, } I,b = multidict({1:7, 2:10000}) model = mkp(I, J, v, a, b) model.ModelSense = -1 model.optimize() print "Optimal value=", model.ObjVal EPS = 1.e-6 for v in model.getVars(): if v.X > EPS: print v.VarName,v.X

The solution of this example is found by Gurobi: \(x_2=x_3=1, x_1=x_4=0\) . We will next briefly sketch how this solution is found.

Branch-and-bound ¶

Many optimization problems, such as knapsack problems, require the solutions to have integer values. In particular, variables in the knapsack problem require values of either 1 or 0 for making decision on whether to include an item in the knapsack or not. Simplex method cannot be used directly to solve for such solution values because it cannot be used to capture the integer requirements on the variables. We can write the constraints \(0 \le x_j \le 1\) for all \(j\) for the binary requirements on the variables, but the simplex method may give fractional values for the solution. Therefore, in general, solving integer-optimization models is much harder. However, we can use a systematic approach called branch-and-bound for solving an integer-optimization model, using the simplex method for solving linear-optimization relaxation model obtained by “relaxing” any integer requirement on the variables to non-negatives only. The process begins with the linear-optimization relaxation of the integer-optimization model and solves several related linear-optimization models by simplex method for ultimately finding an optimal solution of the integer-optimization model.

Let us use the previous knapsack example to illustrate this procedure. We can transform this integer-optimization model of the knapsack problem to its linear-optimization relaxation by replacing the binary requirements by the constraints \(0 \le x_j \le 1\) for all \(j\) . All feasible solutions of the integer-optimization model are also feasible for this linear-optimization relaxation; i.e., the polyhedron of the integer-optimization model is now contained within the polyhedron of its linear-optimization relaxation.

This linear-optimization relaxation can be solved easily by the simplex method. If the optimal solution found is feasible to the integer-optimization model also — i.e., it satisfies the binary constraints also, then we have found the optimal solution to the integer-optimization model. Otherwise, for this maximization problem, we can use the value of the optimal solution of the linear-optimization relaxation as the upper bound on the maximum value any solution of the integer-optimization model can possibly attain. Thus, optimal solution value of the linear-optimization relaxation provides an upper bound for the optimal solution value of the underlying integer-optimization model; this information can be suitably used for solving integer-optimization model via solving several related linear-optimization models.

The general notion of branch-and-bound scheme is to use bound on the optimal solution value in a tree search, as shown in Figure  Branch-and-bound . Each leaf of the tree represents some linear-optimization relaxation of the original integer-optimization model. We start at the root of the search tree with the linear-optimization relaxation of the original integer-optimization model. Simplex method, gives the optimal solution \(x = (1,1,0.5,0)\) and objective function value 46.5. Since \(x_3 = 0.5\) is not integer and for the original integer-optimization model we need the variables to be either 0 or 1, we create two different subproblem children of the root by forcing \(x_3 =1\) and \(x_3 = 0\) , say \(P1\) and \(P2\) , respectively. Their optimal solutions are \(x= ( 1,1,0,0.4)\) with objective value 46.2 and \(x= (1, 0.333,1,0)\) with objective value 45.333, respectively. Now these two subproblems can be expanded again by branching on their fractional values just as before. The process will yield a binary search tree because \(x_j\) can only take values of 0 and 1.

FIGS/bbmkp.png

Branch-and-bound

Consider the two children of \(P1\) , \(P3\) and \(P4\) . As found, the optimal solutions for \(P3\) and \(P4\) are \(x = (0,1,1,0)\) with objective function value 42 and \(x = (1,0,1,0.2)\) with objective function value 44.6, respectively. Since \(P3\) gives us a feasible solution for the integer-optimization model, we have an incumbent solution \(x = (0,1,1,0)\) with value 42. If no other feasible solution to the integer-optimization model from the tree search produces objective value larger than 42, then the incumbent is the optimal solution.

As can be seen from this small example, exploring the whole solution space can lead to a very large number of computations, as the number of nodes may potentially duplicate from one level to the other. Gurobi uses branch-and-bound in connection to other advanced techniques, such as the cutting plane approach, in order to achieve a very good performance on this process. As we will see later (e.g., in Chapter  Graph problems ), there are some limitations to the size of the problems that can be tackled by Gurobi; however, a very large number of interesting, real-world problems can be solved successfully. In other situations, even if Gurobi cannot find the optimal solution, it will find a solution close to the optimum within reasonable time; in many applications, this is enough for practical implementation.

The Modern Diet Problem ¶

In this section we consider a mathematical model for maximizing diversity of diet intakes, subject to nutritional requirements and calorie restrictions. Let \(\mathcal{F}\) be a set of distinct foods and \(\mathcal{N}\) be a set of nutrients. Let \(d_{ij}\) be the amount of nutrient \(i\) in food \(j\) . The minimum and maximum intake of each nutrient \(i\) is given by \(a_i\) and \(b_i\) , respectively. An upper bound for the quantity of each food is given by \(M\) . Let \(x_j\) be the number of dishes to be used for each food \(j\) , and let \(y_j=1\) indicate if food \(j\) is chosen, \(y_j=0\) if not. Let the cost of the diet be \(v\) and the amount of intake of each nutrient be given by \(z_i\) . The problem is to minimize the number of distinct foods.

The first set of constraints ( Nutr in the program below) calculate the amount of each nutrient by summing over the selection of foods. Together with the last set of constraints (which is entered as bounds on \(z\) , line 8 in the program below), they ensure that nutrient levels \(z_i\) are maintained within the maximum and minimum amounts, \(a_i\) and \(b_i\) , as required. The second set of constraints ( Eat in the program below) impose that a dish variety \(y_j\) will be allowed into the objective (i.e., be non-zero) only if at least one unit of that dish \(x_j\) is selected. The third constraint ( Cost , line 16 in the program) calculates cost \(v\) of selecting a diet, while the other two constraints impose non-negativity and binary requirements on the variables \(x_j\) and \(y_j\) defined earlier.

In Python/Gurobi, this model can be specified as follows.

def diet(F, N, a, b, c, d): model = Model("modern diet") x, y, z = {}, {}, {} for j in F: x[j] = model.addVar(lb=0, vtype="I", name="x[%s]" % j) y[j] = model.addVar(vtype="B", name="y[%s]" % j) for i in N: z[i] = model.addVar(lb=a[i], ub=b[i], name="z[%s]" % j) v = model.addVar(name="v") model.update() for i in N: model.addConstr(quicksum(d[j][i]*x[j] for j in F) == z[i], "Nutr[%s]" % i) model.addConstr(quicksum(c[j]*x[j] for j in F) == v, "Cost") for j in F: model.addConstr(y[j] <= x[j], "Eat[%s]" % j) model.setObjective(quicksum(y[j] for j in F), GRB.MAXIMIZE) model.__data = x, y, z, v return model

We may use the data provided in http://www.ampl.com/EXAMPLES/MCDONALDS/diet2.dat for applying this model to a concrete instance:

inf = GRB.INFINITY N, a, b = multidict({ "Cal" : [ 2000, inf ], "Carbo" : [ 350, 375 ], "Protein" : [ 55, inf ], "VitA" : [ 100, inf ], "VitC" : [ 100, inf ], "Calc" : [ 100, inf ], "Iron" : [ 100, inf ], }) F, c, d = multidict({ "QPounder":[1.84, {"Cal":510, "Carbo":34, "Protein":28, "VitA":15, "VitC": 6, "Calc":30, "Iron":20}], "McLean" :[2.19, {"Cal":370, "Carbo":35, "Protein":24, "VitA":15, "VitC": 10, "Calc":20, "Iron":20}], "Big Mac" :[1.84, {"Cal":500, "Carbo":42, "Protein":25, "VitA": 6, "VitC": 2, "Calc":25, "Iron":20}], "FFilet" :[1.44, {"Cal":370, "Carbo":38, "Protein":14, "VitA": 2, "VitC": 0, "Calc":15, "Iron":10}], "Chicken" :[2.29, {"Cal":400, "Carbo":42, "Protein":31, "VitA": 8, "VitC": 15, "Calc":15, "Iron": 8}], "Fries" :[ .77, {"Cal":220, "Carbo":26, "Protein": 3, "VitA": 0, "VitC": 15, "Calc": 0, "Iron": 2}], "McMuffin":[1.29, {"Cal":345, "Carbo":27, "Protein":15, "VitA": 4, "VitC": 0, "Calc":20, "Iron":15}], "1%LFMilk":[ .60, {"Cal":110, "Carbo":12, "Protein": 9, "VitA":10, "VitC": 4, "Calc":30, "Iron": 0}], "OrgJuice":[ .72, {"Cal": 80, "Carbo":20, "Protein": 1, "VitA": 2, "VitC":120, "Calc": 2, "Iron": 2}], })

In this specification of data we have used a new feature of the multidict function: for the same key (e.g., nutrients), we may specify more than one value, and assign it to several Python variables; for example, in line 3 we are specifying both the minimum and the maximum intake amount concerning calories; respectively, a and b . We are now ready to solve the diet optimization model; let us do it for several possibilities concerning the maximum calorie intake b["Cal"] :

The data is specified in lines 1 through 43. In lines 45 to 58, we solve this problem for different values of the maximum calorie intake, from infinity (i.e., no upper bound on calories) down to 2500. We encourage the reader to use Python/Gurobi to solve this problem, and check that the variety of dishes allowed decreases when the calorie intake is reduced. Interestingly, the amount spent does not vary monotonously: among those values of the calorie intake, the minimum price is for a maximum of calories of 3500 (see also Appendix dietinput ).

As said before, until recently these were called problems, which had been abbreviated as ; complying to the new nomenclature, the abbreviation we will use is , for problems.
A class of problems which, even though no one proved it, are believed to be difficult to solve; i.e., solving these problems requires resources that grow exponentially with the size of the input.
Of course “anything” is an exaggeration. In a Python lecture found at the Massachusetts Institute of Technology home page there is a reference to an antigravity module. Please try it with antigravity.
Sometimes it is called a barrier method.
A problem with all the parameters substituted by numerical values is called ; this meaning is different of “objects generated from a class”, used in object-oriented programming, which are also called “instances” of the class.

logo

Free College Algebra Course with Python Code: A Comprehensive Expert Guide

' data-src=

Algebra provides critical skills for solving complex problems and unlocking careers in technology, engineering, science, and beyond. That‘s why I‘m thrilled to showcase this free full-semester college algebra course from freeCodeCamp, taught by an experienced university math professor who is also an expert Python coder.

In this comprehensive 2600+ word guide, I‘ll leverage my expertise as a full-stack developer to explore the course in-depth, including expanded coverage of the coding curriculum, supplemental resources, real-world applications, and the immense value of algebra for aspiring technologists.

College Algebra Course Thumbnail

Photo by Marten Bjork on Unsplash

What Makes This Algebra Course Special

While there are many free college algebra courses available online, this course from freeCodeCamp.org stands out in two important ways:

1. It‘s taught by an experienced math professor and Python developer. The instructor, Ed Pratowski, has years of university-level math teaching experience paired with expert-level Python coding abilities. This rare combination enables him to effectively teach abstract algebraic concepts while grounding lessons in concrete real-world coding examples.

2. Hands-on coding projects reinforce concepts. Rather than just seeing formulas and graphs, students use Python in Google Colab notebooks to code algebraic functions, solve problems, and visualize solutions. Creating these mini-programs cements understanding and builds valuable programming skills.

Additionally, the full 15-week curriculum is structured as a university-level semester-long course and available entirely for free on YouTube.

Who This Course Is For: Key Audiences

This algebra course is designed for a wide range of learners – both those new to algebra and those looking to fill in gaps. Specific audiences who may benefit include:

Aspiring Engineers & Computer Scientists: Algebra skills are non-negotiable for technical careers, with coding amplifying usefulness. High schoolers can build readiness. College students can solidify understanding.

Data Science & Analysis Hopefuls: Mathematically expressing relationships between variables is the foundation of modeling data. Algebra feeds directly into learning data science programming.

Career Changers: As more roles demand tech literacy, algebra and programming help transition careers. The course is paced for beginners.

Lifelong Learners: Even recreational learners can benefit from sharpening logical thinking and analysis abilities through algebra. And the coding element adds valuable real-world skills.

The hybrid course format does involve hands-on coding, so some prior programming experience can be helpful for faster traction. However, instructor walkthroughs allow coding novices to also build skills over time.

Course Curriculum Walkthrough: Key Algebra Topics

Over 15 weeks, this course methodically builds algebraic skill and coding technique covering all the core concepts in a typical college algebra course:

Week 1: Ratios, Proportions, Conversions

  • Define variables, set up proportions, solve proportions
  • Python coding: variables, if statements, modulus

Week 2: Linear Equations (One Variable)

  • Solving equations via addition/subtraction
  • Python: sympysolve symbolic math module

Week 3: Fractions, Decimals, Percents

  • Connect representations, convert between forms
  • Python: clean fractional/decimal conversions

Week 4: Functions, Multiple Variables

  • Relationships between inputs and outputs
  • Python: generate/plot coordinate tables

Week 5: Slope, Graphing Lines

  • Find slope from graph or points, linear equation forms
  • Python: matplotlib plots, numpy linspaces

Week 6: Factoring, Simplifying

  • Factor out greatest common terms
  • Python: Factorization, reduction loops

Week 7: Graphing Systems of Equations

  • Visualize intersections of two equations
  • Python: Plot two equation lines

Week 8: Solving Systems of Equations

  • Algebraically solve two variables per equation set
  • Python: Symbolic solution, numerically approximate

Week 9: Linear System Word Problems

  • Model real-world scenarios as equation pairs
  • Python: Logic to construct systems

Week 10: Quadratic Equations

  • Vertex forms, discriminate, factorization
  • Python: Dynamic parameterizable graphs

Week 11: Polynomials & Parent Graphs

  • Forms, transformations, connections to exponents
  • Python: General high-order polynomial graphs

Week 12: Costs, Revenues, Profits

  • Model business scenarios across variables
  • Python: Surfaces, optimize profits

Week 13: Exponents, Logarithms

  • Scientific notation, compound interest forms
  • Python: exponential curves, logistic growth

Weeks 14-15: Final Projects & Growth

  • Cement core concepts, link algebra to real-world data/models
  • Python: personalized data analysis

As evident by the syllabus walkthrough, this course goes far beyond textbook equations. The coding projects create meaningful connections between abstract symbols and tangible programming output.

Why Algebra Matters for Tech Careers

Beyond the intrinsic intellectual value of understanding algebraic abstraction, math and programming skills enable exciting and lucrative technology careers.

It‘s no secret that software engineering and developer roles top pay rankings year over year . The Bureau of Labor Statistics projects over 22% growth for these positions over the next decade, with six-figure average pay .

And developers are just one piece of the industry puzzle. Careers throughout the entire tech stack depend on mathematical competence , from data scientists and machine learning engineers to business and systems analysts.

Chart showing high average pays for tech careers

Average Salaries for Technology Careers Requiring Math Proficiency (Source)

College algebra specifically establishes critical capacities for logical and computational thinking :

  • Abstractly modeling real-world systems
  • Identifying meaningful patterns and variables
  • Designing functions, training predictive models
  • Analyzing and optimizing complex processes

Whether you aim to be running regression analyses or recursion algorithms, algebraic intuition provides a key foundation.

Combined with coding applications, the algebra lessons in this course directly equip learners for continuing into specialized technical fields.

Comparison to Other Algebra Courses

While algebra has become a staple offering among major online course providers, most lack key elements that set the freeCodeCamp course apart:

Khan Academy: Wide range of math content but algebra videos are purely theoretical. No coding applications. Instructor not a programmer.

EdX: College algebra courses available but most still traditional lecture/textbook style. Some coding options but additional paid certifications.

Coursera: Specialized advanced algebra offerings common but few beginner-oriented. And still no integrated coding or custom solutions.

Udemy/Skillshare: Quality varies widely based on instructor. Most very short form without ongoing support. Success depends heavily on self-direction.

Ultimately, none match the expert instruction, coding interactivity, and comprehensive curriculum that the freeCodeCamp algebra course provides, complete with full-semester scope.

For motivated learners, it represents an unparalleled opportunity to build enduring algebraic competence and programming abilities without any financial barriers.

Real-World Algebra Applications

While abstract in isolation, algebra offers immense power to model real-world phenomena when paired with code implementation:

Data Science: Connecting abstract variables to real datasets via NumPy arrays or Pandas DataFrames

Finance: Using algebra to express interest rates, investments, and loans over time through Python

Science: Transforming mathematical relationships into simulation models of physics, biology, and chemistry systems

Machine Learning: Establishing statistical relationships between input data and target variables that ML models exploit

Economics: Equilibriums, supply and demand, marginal costs/revenue and associated optimizations

Social Sciences: Quantifying and predicting human behavior patterns, perceptions, decision variances

These examples just brush the surface of applied use cases. Core algebraic functions underpin many mission-critical processes across industries. Paired with coding implementations, the possibilities expand exponentially.

Supplemental Resources To Further Math Progress

While comprehensively covering typical college algebra curriculum, focused supplemental materials can help cement and even extend concepts:

Wolfram Alpha: Sophisticated computational knowledge engine useful for checking algebraic work and explorations. Can explain step-by-step solutions. Offer targeted recommendations based on gaps.

GeoGebra: Open-source graphing applet ideal for intuitive understanding before coding visualizations. Features 3D graphing, slider variables, and even calculus tools. Built-in algebra and geometry lessons available too.

Microsoft Math Solver: User-friendly algebra/calculus problem solving tool and grapher. Excellent for double-checking or walking through hairy multiline solutions. Fully explained step-by-step solutions.

Schaum‘s Math Guides: Classic series covering algebra, geometry, calculus, differential equations, and more. Concise explanations with targeted problem sets to practice core competencies. Get older editions cheaply.

Algebra Desmos Activities: Self-paced explorations of concepts like quadratic functions, transformations, factoring. Great for building graphical intuition before equations or coding.

The course instructor, Ed Pratowski, also maintains an excellent YouTube channel with further algebraic content including pre-calculus. Well worth reviewing and subscribing!

Conclusion: Invest in Transferable Skills

For any technology career path, few skills open more doors than fluent algebraic and programming abilities. This free college algebra course from freeCodeCamp offers an accessible on-ramp complete with expert instruction and hands-on coding.

The content breadth provides rock-solid conceptual foundations while the programming integration encourages practical applications. Supplemental with targeted graphical practice, extra problem sets, and leveraging powerful computational tools, and you have a recipe for excel

Whether you‘re pursuing a degree/certification, advancing your career, or just looking to exercise your mind – don‘t underestimate algebra. Combined with coding implementations, you gain a framework for understanding the world and a springboard to keep reaching higher. This course helps set you up for long-term success.

' data-src=

Dr. Alex Mitchell is a dedicated coding instructor with a deep passion for teaching and a wealth of experience in computer science education. As a university professor, Dr. Mitchell has played a pivotal role in shaping the coding skills of countless students, helping them navigate the intricate world of programming languages and software development.

Beyond the classroom, Dr. Mitchell is an active contributor to the freeCodeCamp community, where he regularly shares his expertise through tutorials, code examples, and practical insights. His teaching repertoire includes a wide range of languages and frameworks, such as Python, JavaScript, Next.js, and React, which he presents in an accessible and engaging manner.

Dr. Mitchell’s approach to teaching blends academic rigor with real-world applications, ensuring that his students not only understand the theory but also how to apply it effectively. His commitment to education and his ability to simplify complex topics have made him a respected figure in both the university and online learning communities.

Similar Posts

How to Build a URL Shortener in Deno: An Expert Guide

How to Build a URL Shortener in Deno: An Expert Guide

Introduction URL shorteners are used to create shorter, more readable links from long URLs. They perform…

Angular Structural Directive Patterns – What They Are and How to Use Them: A Complete 3200+ Word Guide

Angular Structural Directive Patterns – What They Are and How to Use Them: A Complete 3200+ Word Guide

Structural directives are one of the killer features of Angular that allow developers to build dynamic…

The SQL Handbook – A Free Course for Web Developers

The SQL Handbook – A Free Course for Web Developers

Structured Query Language (SQL) is the backbone of nearly every modern web application. According to research…

37 New Android Libraries Every Developer Should Know in 2023

37 New Android Libraries Every Developer Should Know in 2023

The Android developer ecosystem shows no signs of slowing down. Innovative builders continue releasing open-source libraries…

Beyond Regular Expressions: A Deep Dive into Parsing Context-Free Grammars

Photo by John Schnobrich on Unsplash As an experienced full-stack developer, regular expressions are one of…

Turbocharge Your Coding with 15 Must-Have Linux Utilities

Turbocharge Your Coding with 15 Must-Have Linux Utilities

For modern software engineers, mastering command line productivity is mandatory. While fancy IDEs and editors grab…

Discover the Top 75 Free Courses for August

mathematical problem solving using python coursera

Udemy Announces Layoffs Without Saying ‘Layoffs’

Udemy’s latest ‘Strategic Business Update’ uses corporate euphemisms to signal job cuts while pivoting to enterprise clients.

  • 10 Best Free Programming Courses for 2024
  • 7 Best Reverse Engineering Courses for 2024
  • 10 Best Organic Chemistry Courses for 2024
  • 10 Best Applied AI & ML Courses for 2024
  • 7 Best Sketch Courses for 2024

600 Free Google Certifications

Most common

  • project management
  • cyber security

Popular subjects

Graphic Design

Digital Marketing

Communication Skills

Popular courses

The Bible's Prehistory, Purpose, and Political Future

De-Mystifying Mindfulness

Paleontology: Theropod Dinosaurs and the Origin of Birds

Organize and share your learning with Class Central Lists.

View our Lists Showcase

Class Central is learner-supported. When you buy through links on our site, we may earn an affiliate commission.

Problem Solving, Python Programming, and Video Games

University of Alberta via Coursera Help

  • Module 0: Introduction
  • In Module 0, you will meet the instructional team and be introduced to the four themes of this course: computer science, problem solving, Python programming, and how to create video games.
  • Module 1: Design Hacking Version 1
  • In Module 1, you will explore the game creation process that is used in this course. You will use this process to design Version 1 of the first game, Hacking. You will use two problem-solving techniques: problem decomposition and algorithms. You will explore five criteria for problem decomposition: experiential decomposition, feature selection, problem refinement, spatial decomposition, and temporal decomposition. To create your design for Hacking Version 1, you will use three interactive learning objects: the description builder, functional test plan builder, and algorithm builder.
  • Module 2: Program Hacking Version 1
  • In Module 2, you will discover how lexics, syntax, and semantics can be used to understand and describe programming languages. You will use these concepts to understand your first Python statement (expression statement), first three Python expressions (literal, identifier, function call), and first five Python types (int, str, float, function, NoneType). You will use these Python constructs to write, test, and debug Hacking Version 1, a text-based game version. You will then reflect on your game version by using a third problem-solving technique called abstraction, including the specific technique of solution generalization, to solve similar problems.
  • Module 3: Hacking Version 2
  • In Module 3, you will identify solution issues in your game. You will apply a second form of the abstraction problem-solving technique, called using templates, to solve a solution issue by using a graphics library. You will then use lexics, syntax, and semantics to learn two new Python statements (assignment, import), two new Python expressions (binary expression, attribute reference), and one new Python type (module). You will employ these Python constructs and a simple graphics library to write, test, and debug Hacking Version 2.
  • Module 4: Hacking Version 3
  • In Module 4, you will modify your game design to support multiple gameplay paths using a new problem decomposition criteria called case-based decomposition, which utilizes a selection control structure. You will learn one new Python statement (if), one new Python expression (unary expression), and one new Python type (bool). You will employ these Python constructs to write, test, and debug Hacking Version 3.
  • Module 5: Hacking Version 4 & 5
  • In Module 5, you will modify your game design using two new abstraction techniques, called control abstraction and data abstraction. You will explore two different control abstractions, called definite and indefinite repetition. You will learn two new Python statements (for, while), four new Python expressions (subscription expression, expression list, parenthesized expression, list display), and three new Python types (tuple, list, range). You will employ these Python constructs to write, test, and debug Hacking Version 4 and Hacking Version 5.
  • Module 6: Hacking Version 6
  • In Module 6, you will learn a new control abstraction called a user-defined function. You will learn how to implement user-defined functions using two new Python statements (function definition, return). You will employ these Python constructs to significantly improve the quality of your code in Hacking Version 6.
  • Module 7: Hacking Version 7
  • In Module 7, you will not learn any new problem-solving techniques or Python language features. Instead you will exercise your problem-solving skills and practice the language constructs you already know to improve your proficiency. You will add some fun features to the Hacking game by designing, coding, testing, and debugging Hacking Version 7.
  • Module 8: Poke the Dots Version 1 & 2
  • In Module 8, you will design and implement Version 1 of a new graphical game called Poke the Dots. You will then modify your game design using data abstraction to create user-defined classes. You will learn two new Python statements (class definition, pass) that will allow you to construct your own Python types. You will employ these Python constructs to implement Poke the Dots Version 2.
  • Module 9: Poke the Dots Version 3
  • In Module 9, you will not learn any new problem-solving techniques or Python language features. Instead you will exercise your problem-solving skills and practice the language constructs you already know to improve your proficiency. You will add some fun features to the Poke the Dots game by designing, coding, testing, and debugging Poke the Dots Version 3.
  • Module 10: Poke the Dots Version 4
  • In Module 10, you will modify your game design using a new form of control abstraction called user-defined methods. User-defined methods allow you to restrict access to the attributes of a class to improve data abstraction. You will employ user-defined methods to implement Poke the Dots Version 4.
  • Module 11: Poke the Dots Version 5
  • In Module 11, you will not learn any new problem-solving techniques or Python language features. Instead you will exercise your problem-solving skills and practice the language constructs you already know to improve your proficiency. You will add some fun features to the Poke the Dots game by designing, coding, testing, and debugging Poke the Dots Version 5.

Duane Szafron and Paul Lu

Related Courses

Computational thinking for problem solving, introduction to python, python basics: create a guessing number game from scratch, introduction to programming, computer science fundamentals, algorithmic thinking (part 2), related articles, 1700 coursera courses that are still completely free, 250 top free coursera courses of all time, massive list of mooc-based microcredentials.

4.0 rating, based on 4 Class Central reviews

4.3 rating at Coursera based on 226 ratings

Select rating

Start your review of Problem Solving, Python Programming, and Video Games

  • AA Anonymous 4 years ago A great introduction to concepts in coding. I now feel much more confident in my ability to solve coding problems, even if the way forward isn't immediately obvious. I felt that the learning materials were well presented and put together, and that the instructor feedback in the forums was vary helpful. I also thought that the exercises were well designed in teaching you not just the syntax of python, but in getting the learner to solve problems and read the language documentation on their own. It is one thing to be shown how to solve a problem, an other to be given the tools to do so on your own. Helpful
  • AA Anonymous 3 years ago As a complete newbie, I made extensive use of the generous and available tutoring. The responses to my queries were promptly answered and helpful. Helpful
  • AA Anonymous 1 year ago I am very disappointed. They are mixing a parsing class, a beginner python class and a video game course. It is not at all needed. Those who are writing video games are probably not going deep into theory of computer science. They discuss assignment statements and creating a graphics based game in the same lesson! I think they mix up too much into one course. Helpful
  • AA Anonymous 3 years ago The program should have a main menu, through which the user can choose whether he wants to encrypt a text or decrypt it. Helpful

Never Stop Learning.

Get personalized course recommendations, track subjects and courses with reminders, and more.

  • Table of Contents
  • Scratch ActiveCode
  • Navigation Help
  • Help for Instructors
  • About Runestone
  • Report A Problem
  • 1. Introduction
  • 2. Analysis
  • 3. Basic Data Structures
  • 4. Recursion
  • 5. Sorting and Searching
  • 6. Trees and Tree Algorithms
  • 7. Graphs and Graph Algorithms

Problem Solving with Algorithms and Data Structures using Python ¶

By Brad Miller and David Ranum, Luther College (as remixed by Jeffrey Elkner)

  • 1.1. Objectives
  • 1.2. Getting Started
  • 1.3. What Is Computer Science?
  • 1.4. What Is Programming?
  • 1.5. Why Study Data Structures and Abstract Data Types?
  • 1.6. Why Study Algorithms?
  • 1.7. Review of Basic Python
  • 1.8.1. Built-in Atomic Data Types
  • 1.8.2. Built-in Collection Data Types
  • 1.9.1. String Formatting
  • 1.10. Control Structures
  • 1.11. Exception Handling
  • 1.12. Defining Functions
  • 1.13.1. A Fraction Class
  • 1.13.2. Inheritance: Logic Gates and Circuits
  • 1.14. Summary
  • 1.15. Key Terms
  • 1.16. Discussion Questions
  • 1.17. Programming Exercises
  • 2.1. Objectives
  • 2.2. What Is Algorithm Analysis?
  • 2.3. Big-O Notation
  • 2.4.1. Solution 1: Checking Off
  • 2.4.2. Solution 2: Sort and Compare
  • 2.4.3. Solution 3: Brute Force
  • 2.4.4. Solution 4: Count and Compare
  • 2.5. Performance of Python Data Structures
  • 2.7. Dictionaries
  • 2.8. Summary
  • 2.9. Key Terms
  • 2.10. Discussion Questions
  • 2.11. Programming Exercises
  • 3.1. Objectives
  • 3.2. What Are Linear Structures?
  • 3.3. What is a Stack?
  • 3.4. The Stack Abstract Data Type
  • 3.5. Implementing a Stack in Python
  • 3.6. Simple Balanced Parentheses
  • 3.7. Balanced Symbols (A General Case)
  • 3.8. Converting Decimal Numbers to Binary Numbers
  • 3.9.1. Conversion of Infix Expressions to Prefix and Postfix
  • 3.9.2. General Infix-to-Postfix Conversion
  • 3.9.3. Postfix Evaluation
  • 3.10. What Is a Queue?
  • 3.11. The Queue Abstract Data Type
  • 3.12. Implementing a Queue in Python
  • 3.13. Simulation: Hot Potato
  • 3.14.1. Main Simulation Steps
  • 3.14.2. Python Implementation
  • 3.14.3. Discussion
  • 3.15. What Is a Deque?
  • 3.16. The Deque Abstract Data Type
  • 3.17. Implementing a Deque in Python
  • 3.18. Palindrome-Checker
  • 3.19. Lists
  • 3.20. The Unordered List Abstract Data Type
  • 3.21.1. The Node Class
  • 3.21.2. The Unordered List Class
  • 3.22. The Ordered List Abstract Data Type
  • 3.23.1. Analysis of Linked Lists
  • 3.24. Summary
  • 3.25. Key Terms
  • 3.26. Discussion Questions
  • 3.27. Programming Exercises
  • 4.1. Objectives
  • 4.2. What Is Recursion?
  • 4.3. Calculating the Sum of a List of Numbers
  • 4.4. The Three Laws of Recursion
  • 4.5. Converting an Integer to a String in Any Base
  • 4.6. Stack Frames: Implementing Recursion
  • 4.7. Introduction: Visualizing Recursion
  • 4.8. Sierpinski Triangle
  • 4.9. Complex Recursive Problems
  • 4.10. Tower of Hanoi
  • 4.11. Exploring a Maze
  • 4.12. Dynamic Programming
  • 4.13. Summary
  • 4.14. Key Terms
  • 4.15. Discussion Questions
  • 4.16. Glossary
  • 4.17. Programming Exercises
  • 5.1. Objectives
  • 5.2. Searching
  • 5.3.1. Analysis of Sequential Search
  • 5.4.1. Analysis of Binary Search
  • 5.5.1. Hash Functions
  • 5.5.2. Collision Resolution
  • 5.5.3. Implementing the Map Abstract Data Type
  • 5.5.4. Analysis of Hashing
  • 5.6. Sorting
  • 5.7. The Bubble Sort
  • 5.8. The Selection Sort
  • 5.9. The Insertion Sort
  • 5.10. The Shell Sort
  • 5.11. The Merge Sort
  • 5.12. The Quick Sort
  • 5.13. Summary
  • 5.14. Key Terms
  • 5.15. Discussion Questions
  • 5.16. Programming Exercises
  • 6.1. Objectives
  • 6.2. Examples of Trees
  • 6.3. Vocabulary and Definitions
  • 6.4. List of Lists Representation
  • 6.5. Nodes and References
  • 6.6. Parse Tree
  • 6.7. Tree Traversals
  • 6.8. Priority Queues with Binary Heaps
  • 6.9. Binary Heap Operations
  • 6.10.1. The Structure Property
  • 6.10.2. The Heap Order Property
  • 6.10.3. Heap Operations
  • 6.11. Binary Search Trees
  • 6.12. Search Tree Operations
  • 6.13. Search Tree Implementation
  • 6.14. Search Tree Analysis
  • 6.15. Balanced Binary Search Trees
  • 6.16. AVL Tree Performance
  • 6.17. AVL Tree Implementation
  • 6.18. Summary of Map ADT Implementations
  • 6.19. Summary
  • 6.20. Key Terms
  • 6.21. Discussion Questions
  • 6.22. Programming Exercises
  • 7.1. Objectives
  • 7.2. Vocabulary and Definitions
  • 7.3. The Graph Abstract Data Type
  • 7.4. An Adjacency Matrix
  • 7.5. An Adjacency List
  • 7.6. Implementation
  • 7.7. The Word Ladder Problem
  • 7.8. Building the Word Ladder Graph
  • 7.9. Implementing Breadth First Search
  • 7.10. Breadth First Search Analysis
  • 7.11. The Knight’s Tour Problem
  • 7.12. Building the Knight’s Tour Graph
  • 7.13. Implementing Knight’s Tour
  • 7.14. Knight’s Tour Analysis
  • 7.15. General Depth First Search
  • 7.16. Depth First Search Analysis
  • 7.17. Topological Sorting
  • 7.18. Strongly Connected Components
  • 7.19. Shortest Path Problems
  • 7.20. Dijkstra’s Algorithm
  • 7.21. Analysis of Dijkstra’s Algorithm
  • 7.22. Prim’s Spanning Tree Algorithm
  • 7.23. Summary
  • 7.24. Key Terms
  • 7.25. Discussion Questions
  • 7.26. Programming Exercises

Acknowledgements ¶

We are very grateful to Franklin Beedle Publishers for allowing us to make this interactive textbook freely available. This online version is dedicated to the memory of our first editor, Jim Leisy, who wanted us to “change the world.”

Indices and tables ¶

  • Module Index
  • Search Page

Creative Commons License

  • Python Home
  • ▼Python Exercises
  • Exercises Home
  • ▼Python Basic
  • Basic - Part-I
  • Basic - Part-II
  • Python Programming Puzzles
  • Mastering Python
  • ▼Python Advanced
  • Python Advanced Exercises
  • ▼Python Control Flow
  • Condition Statements and Loops
  • ▼Python Data Types
  • List Advanced
  • Collections
  • ▼Python Class
  • ▼Python Concepts
  • Python Unit test
  • Python Exception Handling
  • Python Object-Oriented Programming
  • ▼Functional Programming
  • Filter Function
  • ▼Date and Time
  • Pendulum Module
  • ▼File Handling
  • CSV Read, Write
  • ▼Regular Expressions
  • Regular Expression
  • ▼Data Structures and Algorithms
  • Search and Sorting
  • Linked List
  • Binary Search Tree
  • Heap queue algorithm
  • ▼Advanced Python Data Types
  • Boolean Data Type
  • None Data Type
  • Bytes and Byte Arrays
  • Memory Views exercises
  • Frozenset Views exercises
  • NamedTuple exercises
  • OrderedDict exercises
  • Counter exercises
  • Ellipsis exercises
  • ▼Concurrency and Threading
  • Asynchronous
  • ▼Python Modules
  • Operating System Services
  • SQLite Database
  • ▼Miscellaneous
  • Cyber Security
  • Generators Yield
  • ▼Python GUI Tkinter, PyQt
  • Tkinter Home
  • Tkinter Basic
  • Tkinter Layout Management
  • Tkinter Widgets
  • Tkinter Dialogs and File Handling
  • Tkinter Canvas and Graphics
  • Tkinter Events and Event Handling
  • Tkinter Custom Widgets and Themes
  • Tkinter File Operations and Integration
  • PyQt Widgets
  • PyQt Connecting Signals to Slots
  • PyQt Event Handling
  • ▼Python NumPy
  • Python NumPy Home
  • ▼Python urllib3
  • Python urllib3 Home
  • ▼Python Metaprogramming
  • Python Metaprogramming Home
  • ▼Python GeoPy
  • Python GeoPy Home
  • ▼BeautifulSoup
  • BeautifulSoup Home
  • ▼Arrow Module
  • ▼Python Pandas
  • Python Pandas Home
  • ▼Pandas and NumPy Exercises
  • Pandas and NumPy Home
  • ▼Python Machine Learning
  • Machine Learning Home
  • TensorFlow Basic
  • ▼Python Web Scraping
  • Web Scraping
  • ▼Python Challenges
  • Challenges-1
  • ▼Python Mini Project
  • Python Projects
  • ▼Python Natural Language Toolkit
  • Python NLTK
  • ▼Python Project
  • Novel Coronavirus (COVID-19)
  • ..More to come..

Python Math: - Exercises, Practice, Solution

Python math [94 exercises with solution].

[ An editor is available at the bottom of the page to write and execute the scripts.   Go to the editor ]

1. Write a Python program to convert degrees to radians. Note : The radian is the standard unit of angular measure, used in many areas of mathematics. An angle's measurement in radians is numerically equal to the length of a corresponding arc of a unit circle; one radian is just under 57.3 degrees (when the arc length is equal to the radius). Test Data: Degree : 15 Expected Result in radians: 0.2619047619047619 Click me to see the sample solution

3. Write a Python program to calculate the area of a trapezoid. Note : A trapezoid is a quadrilateral with two sides parallel. The trapezoid is equivalent to the British definition of the trapezium. An isosceles trapezoid is a trapezoid in which the base angles are equal so. Test Data: Height : 5 Base, first value : 5 Base, second value : 6 Expected Output: Area is : 27.5 Click me to see the sample solution

5. Write a Python program to calculate the surface volume and area of a cylinder. Note: A cylinder is one of the most basic curvilinear geometric shapes, the surface formed by the points at a fixed distance from a given straight line, the axis of the cylinder. Test Data: volume : Height (4), Radius(6) Expected Output: Volume is : 452.57142857142856 Surface Area is : 377.1428571428571 Click me to see the sample solution

6. Write a Python program to calculate the surface volume and area of a sphere. Note: A sphere is a perfectly round geometrical object in three-dimensional space that is the surface of a completely round ball. Test Data: Radius of sphere : .75 Expected Output : Surface Area is : 7.071428571428571 Volume is : 1.7678571428571428 Click me to see the sample solution

7. Write a Python program to calculate the arc length of an angle. Note: In a planar geometry, an angle is the figure formed by two rays, called the sides of the angle, sharing a common endpoint, called the vertex of the angle. Angles formed by two rays lie in a plane, but this plane does not have to be a Euclidean plane. Test Data: Diameter of a circle : 8 Angle measure : 45 Expected Output : Arc Length is : 3.142857142857143 Click me to see the sample solution

8. Write a Python program to calculate the area of the sector. Note: A circular sector or circle sector, is the portion of a disk enclosed by two radii and an arc, where the smaller area is known as the minor sector and the larger being the major sector. Test Data: Radius of a circle : 4 Angle measure : 45 Expected Output: Sector Area: 6.285714285714286 Click me to see the sample solution

9. Write a Python program to calculate the discriminant value. Note: The discriminant is the name given to the expression that appears under the square root (radical) sign in the quadratic formula. Test Data: The x value : 4 The y value : 0 The z value : -4 Expected Output: Two Solutions. Discriminant value is : 64.0 Click me to see the sample solution

10. Write a Python program to find the smallest multiple of the first n numbers. Also, display the factors. Test Data: If n = (13) Expected Output : [13, 12, 11, 10, 9, 8, 7] 360360 Click me to see the sample solution

11. Write a Python program to calculate the difference between the squared sum of the first n natural numbers and the sum of squared first n natural numbers.(default value of number=2). Test Data: If sum_difference(12) Expected Output : 5434 Click me to see the sample solution

12. Write a Python program to calculate the sum of all digits of the base to the specified power. Test Data: If power_base_sum(2, 100) Expected Output : 115 Click me to see the sample solution

13. Write a Python program to find out if the given number is abundant. Note: In number theory, an abundant number or excessive number is a number for which the sum of its proper divisors is greater than the number itself. The integer 12 is the first abundant number. Its proper divisors are 1, 2, 3, 4 and 6 for a total of 16. Test Data: If is_abundant(12) If is_abundant(13) Expected Output: True False Click me to see the sample solution

14. Write a Python program to find out if the given number is abundant. Note: Amicable numbers are two different numbers so related that the sum of the proper divisors of each is equal to the other number. (A proper divisor of a number is a positive factor of that number other than the number itself. For example, the proper divisors of 6 are 1, 2, and 3.) Test Data: If amicable_numbers_sum(9999) If amicable_numbers_sum(999) If amicable_numbers_sum(99) Expected Output: 31626 504 0 Click me to see the sample solution

15. Write a Python program to return the sum of all divisors of a number. Test Data: If number = 8 If number = 12 Expected Output: 7 16 Click me to see the sample solution

16. Write a Python program to print all permutations of a given string (including duplicates). Click me to see the sample solution

17. Write a Python program to print the first n lucky numbers. Lucky numbers are defined via a sieve as follows. Begin with a list of integers starting with 1 : 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, . . . . Now eliminate every second number : 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, ... The second remaining number is 3, so remove every 3rd number: 1, 3, 7, 9, 13, 15, 19, 21, 25, ... The next remaining number is 7, so remove every 7th number: 1, 3, 7, 9, 13, 15, 21, 25, ... Next, remove every 9th number and so on. Finally, the resulting sequence is the lucky numbers. Click me to see the sample solution

18. Write a Python program to compute square roots using the Babylonian method. Perhaps the first algorithm used for approximating √S is known as the Babylonian method, named after the Babylonians, or "Hero's method", named after the first-century Greek mathematician Hero of Alexandria who gave the first explicit description of the method. It can be derived from (but predates by 16 centuries) Newton's method. The basic idea is that if x is an overestimate to the square root of a non-negative real number S then S / x will be an underestimate and so the average of these two numbers may reasonably be expected to provide a better approximation. Click me to see the sample solution

19. Write a Python program to multiply two integers without using the * operator. Click me to see the sample solution

Calculate magic square

21. Write a Python program to print all primes (Sieve_of_Eratosthenes) smaller than or equal to a specified number. In mathematics, the sieve of Eratosthenes, one of a number of prime number sieves, is a simple, ancient algorithm for finding all prime numbers up to any given limit. It does so by iteratively marking as composite (i.e., not prime) the multiples of each prime, starting with the multiples of 2. Click me to see the sample solution

22. Write a Python program to find the next smallest palindrome of a specified number. Click me to see the sample solution

23. Write a Python program to find the next and previous palindromes of a specified number. Click me to see the sample solution

24. Write a Python program to convert a float to ratio.

Expected Output :

Click me to see the sample solution

25. Write a Python program for the nth Catalan numbers. In combinatorial mathematics, the Catalan numbers form a sequence of natural numbers that occur in various counting problems, often involving recursively-defined objects. They are named after the Belgian mathematician Eugène Charles Catalan (1814 –1894). Click me to see the sample solution

26. Write a Python program to display numbers separated by commas as thousands. Click me to see the sample solution

27. Write a Python program to calculate the distance between two points using latitude and longitude.

28. Write a Python program to calculate the area of a regular polygon.

29. Write a Python program to calculate the wind chill index.

30. Write a Python program to find the roots of a quadratic function.

31. Write a Python program to convert a decimal number to a binary number.

32. Write a Python program to print a complex number and its real and imaginary parts.

33. Write a Python program to add, subtract, multiply, and divide two complex numbers.

34. Write a Python program to get the length and the angle of a complex number.

35. Write a Python program to convert Polar coordinates to rectangular coordinates.

36. Write a Python program to find the maximum and minimum numbers from the specified decimal numbers.

Decimal numbers : 2.45, 2.69, 2.45, 3.45, 2.00, 0.04, 7.25

37. Write a Python program to find the sum of the following decimal numbers and display the numbers in sorted order.

38. Write a Python program to get the square root and exponential of a given decimal number.

Decimal number : 1.44

39. Write a Python program to retrieve the current global context (public properties) for all decimal.

40. Write a Python program to round a specified decimal by setting precision (between 1 and 4).

Sample Number : 0.26598 Original Number : 0.26598 Precision- 1 : 0.3 Precision- 2 : 0.27 Precision- 3 : 0.266 Precision- 4 : 0.2660

41. Write a Python program to round a specified number upwards towards infinity and down towards negative infinity with precision 4.

42. Write a Python program to get the local and default precision.

43. Write a Python program to display fraction instances of the string representation of a number.

Sample data : '0.7', '2.5', '9.32', '7e-1'

44. Write a Python program to create fraction instances of float numbers.

Sample numbers: 0.2, 0.7, 6.5, 6.0

45. Write a Python program to create fraction instances of decimal numbers.

Sample decimal.2' number: Decimal('0), Decimal('0.7'), Decimal('2.5'), Decimal('3.0')

46. Write a Python program to add, subtract, multiply and divide two fractions.

47. Write a Python program to convert a floating point number (PI) to an approximate rational value on the various denominators.

Note: max_denominator=1000000

48. Write a Python program to generate random floating numbers in a specific numerical range.

49. Write a Python program to generate random integers in a specific numerical range.

50. Write a Python program to generate random even integers in a specific numerical range.

51. Write a Python program to get a single random element from a specified string.

52. Write a Python program to shuffle the following elements randomly.

Sample elements : [1, 2, 3, 4, 5, 6, 7]

53. Write a Python program to flip a coin 1000 times and count heads and tails.

54. Write a Python program to print a random sample of words from the system dictionary.

55. Write a Python program to randomly select an item from a list.

56. Write a Python program to calculate the absolute value of a floating point number.

57. Write a Python program to calculate the standard deviation of the following data.

58. Write a Python program to print the floating point of the mantissa, exponent pair.

59. Write a Python program to split the fractional and integer parts of a floating point number.

60. Write a Python program to parse math formulas and put parentheses around multiplication and division.

61. Write a Python program to describe linear regression.

62. Write a Python program to calculate a grid of hexagon coordinates of the given radius given lower-left and upper-right coordinates. The function will return a list of lists containing 6 tuples of x, y point coordinates. These can be used to construct valid regular hexagonal polygons.

63. Write a Python program to create a simple math quiz.

64. Write a Python program to calculate the volume of a tetrahedron.

Note: In geometry, a tetrahedron (plural: tetrahedra or tetrahedrons) is a polyhedron composed of four triangular faces, six straight edges, and four vertex corners. The tetrahedron is the simplest of all the ordinary convex polyhedra and the only one that has fewer than 5 faces.

65. Write a Python program to compute the value of e(2.718281827...) using an infinite series.

66. Write a Python program to create an ASCII waveform.

67. Write a Python program to create a dot string.

68. Write a Python program to create a Pythagorean theorem calculator.

69. Write a Python function to round up a number to specified digits.

70. Write a Python program for a casino simulation.

71. Write a Python program to reverse a range.

72. Write a Python program to create a range for floating numbers.

73. Write a Python program to generate (given an integer n) a square matrix filled with elements from 1 to n raised to the power of 2 in spiral order.

74. Write a Python program to select a random date in the current year.

75. Write a Python program to calculate clusters using the Hierarchical Clustering method.

76. Write a Python program to implement the Euclidean Algorithm to compute the greatest common divisor (GCD).

77. Write a Python program to convert RGB color to HSV color.

78. Write a Python program to find perfect squares between two given numbers.

79. Write a Python program to compute Euclidean distances.

80. Write a Python program to convert an integer to a 2 byte Hex value.

81. Write a Python program to generate a series of distinct random numbers.

82. Write a Python program to convert a given float value to a ratio.

83. Write a Python program to calculate the aliquot sum of a given number.

84. Write a Python program to get the nth tetrahedral number from a given integer(n) value.

85. Write a Python program to get the sum of the powers of all the numbers from start to end (both inclusive).

86. Write a Python program to calculate the Hamming distance between two given values.

87. Write a Python program to cap a number within the inclusive range specified by the given boundary values x and y.

88. Write a Python program to check whether a given number is a Disarium number or an unhappy number.

89. Write a Python program to check if a given number is a repdigit number or not. If the given number is repdigit return true otherwise false. Sample Data: (0) -> True (1) -> True (-1111) -> False (9999999) -> True Click me to see the sample solution

90. Write a Python program to check if a given number is a Harshad number or not. Return True if the number is Harshad otherwise False. Sample Data: (666) -> True (11) -> False (-144) -> None (200) -> True Click me to see the sample solution

91. Write a Python program that accepts an integer number with distinct digits and displays the next number containing only distinct digits. Sample Data: 12345) -> 12346 (99999) -> 102345 (100) -> 102 Click me to see the sample solution

92. Write a Python program that checks whether the absolute difference between two consecutive digits is two or not. Return true otherwise false. Sample Data: (666) -> False (3579) -> True (2468) -> True (20420) -> False Click me to see the sample solution

93. Write a Python program that takes an integer and rearranges the digits to create two maximum and minimum numbers. Click me to see the sample solution

94. Write a Python program to calculate the sum of all prime numbers in a given list of positive integers. Sample Data: ([1, 3, 4, 7, 9]) -> 10 ([]) -> Empty list! ([11, 37, 444]) -> 48 Click me to see the sample solution

Python Code Editor:

More to Come !

Test your Python skills with w3resource's quiz

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends and Language Statistics

IMAGES

  1. Introduction to Linear Algebra and Python

    mathematical problem solving using python coursera

  2. Problem Solving using Python

    mathematical problem solving using python coursera

  3. (PDF) A webinar on Solving Mathematical problems using Python

    mathematical problem solving using python coursera

  4. SOLUTION: Problem solving using python

    mathematical problem solving using python coursera

  5. GitHub

    mathematical problem solving using python coursera

  6. Problem Solving, Python Programming, and Video Games

    mathematical problem solving using python coursera

COMMENTS

  1. Computational Thinking for Problem Solving

    There are 4 modules in this course. Computational thinking is the process of approaching a problem in a systematic manner and creating and expressing a solution such that it can be carried out by a computer. But you don't need to be a computer scientist to think like a computer scientist! In fact, we encourage students from any field of study ...

  2. Applied Calculus with Python

    There are 5 modules in this course. This course is designed for the Python programmer who wants to develop the foundations of Calculus to help solve challenging problems as well as the student of mathematics looking to learn the theory and numerical techniques of applied calculus implemented in Python. By the end of this course, you will have ...

  3. Problem Solving, Python Programming, and Video Games

    1. Take a new computational problem and solve it, using several problem solving techniques including abstraction and problem decomposition. 2. Follow a design creation process that includes: descriptions, test plans, and algorithms. 3. Code, test, and debug a program in Python, based on your design. Important computer science concepts such as ...

  4. Solve problems with Jupyter Notebooks

    Click on the Jupyter logo, which will take you to the file tree view. Select the notebook that you want to download. Note that you'll need to shut down the notebook if it is running. Click Download to download the file as a .ipynb file. If you'd like to download the file in a different format (e.g. PDF, HTML), then you can click the Lab ...

  5. Coursera Computational Thinking for Problem Solving

    You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window.

  6. Mathematics for Machine Learning and Data Science Specialization

    This Specialization uses innovative pedagogy in mathematics to help you learn quickly and intuitively, with courses that use easy-to-follow plugins and visualizations to help you see how the math behind machine learning actually works. This is a beginner-friendly program, with a recommended background of at least high school mathematics.

  7. Computational Thinking for Problem Solving

    About the Course. Computational thinking is the process of approaching a problem in a systematic manner and creating and expressing a solution such that it can be carried out by a computer. But you don't need to be a computer scientist to think like a computer scientist! In fact, we encourage students from any field of study to take this course.

  8. Solving math problems using python (Quick Code-Python)

    We use a library called math, which is a built-in python library to do quick mathematical operations. The function math.sqrt takes the square root of the result y that we got from (task 1) E ...

  9. Simplest way to solve mathematical equations in Python

    There is a browser interface and an API to Python / MATLAB. The API to Python is a single script (apm.py) that is available for download from the apmonitor.com homepage. Once the script is loaded into a Python code, it gives the ability to solve problems of: Nonlinear equations; Differential and algebraic equations; Least squares model fitting

  10. Introduction

    Linear optimization problems with conditions requiring variables to be integers are called integer optimization problems. For the puzzle we are solving, thus, the correct model is: minimize y + z subject to: x + y + z = 32 2x + 4y + 8z = 80 x, y, z ≥ 0, integer. Below is a simple Python/SCIP program for solving it.

  11. Introduction to Linear Algebra and Python

    Introduction to Matrices and Linear Algebra. Module 1 • 4 hours to complete. In module 1, you'll learn how to explain fundamental concepts of linear algebra and how to use Python, one of the most powerful programming languages, to model different data. We will cover the following learning objectives. What's included.

  12. Computational Thinking & Problem Solving: UPenn Coursera

    Artificial/informal, text-based language that helps develop and organize future algorithms. A set of base, step-by-step instructions written for humans to better understand what to ask in a computer algorithm. Study with Quizlet and memorize flashcards containing terms like Computational Thinking, Four Pillars of Computational Thinking ...

  13. shantanu1109/Coursera-Imperial-College-of-London-Mathematics-For

    Through the assignments of this specialisation you will use the skills you have learned to produce mini-projects with Python on interactive notebooks, an easy to learn tool which will help you apply the knowledge to real world problems. For example, using linear algebra in order to calculate the page rank of a small simulated internet, applying ...

  14. Solving Vehicle Routing Problems with Python & Heuristics ...

    5. Coding the CVRP Model with Python. Here is the Vehicle Routing Problem implementation using the Nearest Neighbor heuristic. I have utilized the Spyder IDE and an academic license for Gurobi to ...

  15. Free College Algebra Course With Python Code: A Comprehensive Expert

    Microsoft Math Solver: User-friendly algebra/calculus problem solving tool and grapher. Excellent for double-checking or walking through hairy multiline solutions. Fully explained step-by-step solutions. Schaum's Math Guides: Classic series covering algebra, geometry, calculus, differential equations, and more. Concise explanations with ...

  16. Problem Solving, Python Programming, and Video Games

    This course is an introduction to computer science and programming in Python. Upon successful completion of this course, you will be able to: 1. Take a new computational problem and solve it, using several problem solving techniques including abstraction and problem decomposition. 2.

  17. Best Problem Solving Courses Online with Certificates [2024]

    In summary, here are 10 of our most popular problem solving courses. Effective Problem-Solving and Decision-Making: University of California, Irvine. Creative Thinking: Techniques and Tools for Success: Imperial College London. Solving Problems with Creative and Critical Thinking: IBM. Computer Science: Programming with a Purpose: Princeton ...

  18. Problem Solving with Algorithms and Data Structures using Python

    An interactive version of Problem Solving with Algorithms and Data Structures using Python. ... Problem Solving with Algorithms and Data Structures using Python by Bradley N. Miller, David L. Ranum is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Next Section - 1. Introduction

  19. Python Math: Exercises, Practice, Solution

    Expected Output : Quadratic function : (a * x^2) + b*x + c a: 25 b: 64 c: 36 There are 2 roots: -0.834579 and -1.725421. Click me to see the sample solution. 31. Write a Python program to convert a decimal number to a binary number. Expected Output : Input a binary number: 101011 The decimal value of the number is 43.

  20. mathematics-machine-learning · GitHub Topics · GitHub

    This repository contains a comprehensive collection of mathematical concepts and techniques relevant to various fields of AI, including ML, DL & other areas.It also includes the corresponding source code for all programming tasks associated with the Mathematics for Machine Learning courses, which are taught at Coursera by Imperial College London.

  21. Mathematics for Machine Learning: Linear Algebra

    Introduction to Linear Algebra and to Mathematics for Machine Learning. Module 1 • 2 hours to complete. In this first module we look at how linear algebra is relevant to machine learning and data science. Then we'll wind up the module with an initial introduction to vectors. Throughout, we're focussing on developing your mathematical ...

  22. coursera-solutions · GitHub Topics · GitHub

    All my solved ASSIGNMENTS & QUIZZES in Python Data Structure course on COURSERA using Python 3. python coursera python3 coursera-assignment coursera-python python-data-structures coursera ... Solutions to Algorithmic Problems from Coursera Course. coursera toolbox alogrithms coursera-solutions Updated Feb 17, 2023; Java; THammami01 ...

  23. Python Programming Fundamentals

    There are 4 modules in this course. This introductory course is designed for beginners and individuals with limited programming experience who want to embark on their software development or data science journey using Python. Throughout the course, learners will gain a solid understanding of algorithmic thinking, Python syntax, code testing ...

  24. Discrete-Math-Specialization-Coursera-/5.Delivery Problem ...

    This repository contains the materials, python codes for the quiz and some codes implemented using jupyter notebook related to the specialization ( Introduction to Discrete Mathematics In Computer ...

  25. Best Software Development Courses Online with Certificates [2024

    Skills you'll gain: Software Engineering, Agile Software Development, Design and Product, Problem Solving, Software Architecture, Software Testing, Leadership and ...