Aula Pulp
Aula Pulp
Resolvendo modelos de
programação linear inteira com
Python e PuLP
• If your version is not the 3.10 or 3.9, follow the instructions given in
“Python-code editor, interpreter, and first code.pdf”.
The Basic Python Syntax
• The Python syntax is clear, concise, and focused on readability.
• Readability is one of the more attractive features of the language itself.
• It makes Python ideal for people who are learning to program.
• Some components of the Python syntax:
• Comments
• Variables
• Keywords
• Built-in data types
• Conditional statements
• Loops
• Functions
Python Indentation
• Indentation refers to the spaces at the beginning of a code line.
• Where in other programming languages the indentation in code
is for readability only, the indentation in Python is very
important.
• Python uses indentation to indicate a block of code.
• The number of spaces is up to you as a programmer, but it has
to be at least one:
• We have to use the same number of spaces in the same block of code;
otherwise Python will give you an error.
Python Indentation
• In languages like C, C++, Java, we use curly braces { } to
indicate the start and end of a block of code.
• In Python, we use space/tab as indentation to indicate the
same to the interpreter:
• To avoid errors: use the tab button to indent the code.
Python Indentation
• Some examples:
Comments
• Comments are pieces of text that live in your code but are
ignored by the Python interpreter as it executes the code.
• You can use comments to describe the code so that you and
other developers can quickly understand what the code does or
why the code is written in a given way.
• In general, your comments should be short and to the point (less
than 72 characters).
• To write a comment in Python, just add a hash mark (#) before
your comment text:
Variables
• They are names attached to a particular object.
• They hold a reference to the memory address at which an object
is stored.
• Once a variable is assigned an object, we can access the object
using the variable name.
• In Python, everything is an object, with at least three pieces of
data:
• Reference count
• Type
• Value
Variables
• We define variables with the syntax:
• Variable names can be any length and can consist of uppercase and
lowercase letters (A-Z, a-z), digits (0-9), and also the underscore
character (_).
• The first character cannot be a digit.
• Use a naming scheme that makes your variables intuitive and readable.
• The variable name should provide some indication as to what the values
assigned to it are.
• Avoid single-character names and use something more descriptive.
• Python is sensitive case language.
VARIABLES
Some examples:
Keywords
• Python has a set of special words that are part of its syntax,
which are called keywords.
• They are reserved words that have specific meanings and
purposes in the language:
• Do not use them for anything but those specific purposes.
Built-In Data Types
• Python has a handful of built-in data types, such
as numbers (integers, floats, complex
numbers), Booleans, strings, lists, tuples, dictionaries,
and sets.
• We can manipulate them with several tools:
• Operators (arithmetic, comparison, logical, bitwise, Identity)
• Built-in functions (abs, all, any, bool, list, len, set, hash, vars, min…)
• Data type methods (class, static, and regular instance methods).
Numbers
• Python provides integers,
floating-point numbers, and
complex numbers.
• Integers and floating-point
numbers are the most used
numeric types in day-to-day
programming.
• Complex numbers have specific
use cases in math and science.
Operations
• Operators represent operations, such as addition,
subtraction, multiplication, division, and so on…
• Python provides you with a bunch of built-in functions for
manipulating numbers.
• There are modules available in the Python standard library,
such as math, that also provide you with functions to
manipulate numbers.
• To use the functions associated with these modules, we first have to
import the module.
• Then, we access the function using module.function_name().
Booleans
• Booleans are implemented as a subclass of integers with
only two possible values in Python: True or False.
• Note that these values must start with a capital
letter.
• We use Boolean values to express the truth value of an
expression or object.
• Booleans are handy when we are
writing predicate functions or when we are
using comparison operators, such as greater than (>),
lower than (<), equal (==), and so on.
Operators
• They are special symbols that designate that some sort of computation
should be performed. The values that an operator acts on are
called operands.
• A sequence of operands and operators, like a + b * 5, is called an
expression.
• All operators that the language supports are assigned a precedence.
• In an expression, all operators of highest precedence are performed
first.
• Once those results are obtained, operators of the next highest
precedence are performed:
• It continues, until the expression is fully evaluated.
• Any operators of equal precedence are performed in left-to-right order.
Arithmetic Operators
Comparison Operators
Logical Operators
OPERATOR
PRECEDENCE
The Standard Library
• One of the great things about Python is the plethora of available
modules, packages, and libraries both built into the Python core and
made available by third-party developers.
• These modules, packages, and libraries can be quite helpful in your day-
to-day work as a Python coder.
• Here are some of the most used built-in modules:
• math for mathematical operations.
• random for generating pseudo-random numbers.
• re for working with regular expressions.
• os for using operating system-dependent functionalities.
• itertools for working with iterators.
• collections for specialized container data types.
The Standard Library
• For example, here we import math to use pi, find the square
root of a number with sqrt(), and raise a number to a power
with pow():
Import
• In Python, we use the import keyword to make code in
one module available in another:
• A module usually corresponds to one .py file containing Python
code.
• Imports in Python are important for structuring the
code effectively.
• Using imports properly will make we more productive,
allowing to reuse code while keeping the projects
maintainable.
Import
• We are now ready to solve the problem .solve() on the model object. It uses the default
solver (CBC):
#solving the model
model.solve()
• solve() calls the underlying solver, modifies the model object, and gives the integer status of the
solution:
PuLP
• We can get the optimization results as the attributes
of model:
• The method value() return the actual values of the attributes:
#printing the status and solution
print("status: ", model.status)
print("objective function: ", model.objective.value())
status: 1
objective function: 16.8181817
x = 7.7272727
y = 4.5454545
PuLP
• The Python program is:
Knapsack Problems
• They involve the choice of objects to be placed in one or
more knapsacks in order to maximize the profit. Some
variants:
• 0-1 Knapsack: there are n projects and capital b for
investment. Each project has the cost aj and an expected
return pj. We want to select a subset of projects that
maximize the total expected return without exceeding
the capital available.
• Integer Knapsack: like the 0-1 Knapsack, but now we
can invest more than once in the same project.
• Multiple Knapsacks: there are n items and m equal
knapsacks of capacity bi. Each item has profit pj and
weight wj. We want m disjoint subset of items, such that
each subset respect the knapsack’s capacity bi and the
total profit is maximum.
0-1 Knapsack Problem
• Parameters:
• n is the number of items (for j = 1, ..., n).
• b is the capacity of the knapsack.
• aj is the weight of item j.
• pj is the value (profit) of item j.
• Variables:
• xj = 1, if item j is chosen.
• xj = 0, otherwise.
0-1 Knapsack Problem
Subject to:
Example 1:
• A Python code for
the 0-1 Knapsack
Problem is:
Output:
• In several industrial processes, items are
Cutting
produced by cutting larger objects.
• These larger objects can have one, two, or
three relevant dimensions such as: