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 |
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.
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.
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.
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.
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.
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.
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.
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. |
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.
Photo by Marten Bjork on Unsplash
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.
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.
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
Week 2: Linear Equations (One Variable)
Week 3: Fractions, Decimals, Percents
Week 4: Functions, Multiple Variables
Week 5: Slope, Graphing Lines
Week 6: Factoring, Simplifying
Week 7: Graphing Systems of Equations
Week 8: Solving Systems of Equations
Week 9: Linear System Word Problems
Week 10: Quadratic Equations
Week 11: Polynomials & Parent Graphs
Week 12: Costs, Revenues, Profits
Week 13: Exponents, Logarithms
Weeks 14-15: Final Projects & Growth
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.
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.
Average Salaries for Technology Careers Requiring Math Proficiency (Source)
College algebra specifically establishes critical capacities for logical and computational thinking :
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.
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.
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.
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!
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.
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.
Introduction URL shorteners are used to create shorter, more readable links from long URLs. They perform…
Structural directives are one of the killer features of Angular that allow developers to build dynamic…
Structured Query Language (SQL) is the backbone of nearly every modern web application. According to research…
The Android developer ecosystem shows no signs of slowing down. Innovative builders continue releasing open-source libraries…
Photo by John Schnobrich on Unsplash As an experienced full-stack developer, regular expressions are one of…
For modern software engineers, mastering command line productivity is mandatory. While fancy IDEs and editors grab…
Udemy’s latest ‘Strategic Business Update’ uses corporate euphemisms to signal job cuts while pivoting to enterprise clients.
600 Free Google Certifications
Graphic Design
Digital Marketing
Communication Skills
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.
University of Alberta via Coursera Help
Duane Szafron and Paul Lu
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
Get personalized course recommendations, track subjects and courses with reminders, and more.
By Brad Miller and David Ranum, Luther College (as remixed by Jeffrey Elkner)
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.”
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
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.
IMAGES
COMMENTS
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 ...
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 ...
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 ...
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 ...
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.
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.
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.
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 ...
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
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.
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.
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 ...
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 ...
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 ...
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 ...
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.
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 ...
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
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.
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.
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 ...
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 ...
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 ...
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 ...
Skills you'll gain: Software Engineering, Agile Software Development, Design and Product, Problem Solving, Software Architecture, Software Testing, Leadership and ...