{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Maxime Labonne",
  "title_listed": "Integer vs. Linear Programming in Python",
  "keywords": "整数规划,线性规划,优化",
  "domain": "机器学习",
  "content_type": "深度技术解析",
  "is_paid_flag": "部分免费/会员墙",
  "url": "https://towardsdatascience.com/integer-programming-vs-linear-programming-in-python-f1be5bb4e60e/",
  "publish_date": "2022-04",
  "corpus_stage": "预训练/SFT",
  "notes": "",
  "id": "db450d041200",
  "collected_at": "2026-10-01T22:13:43",
  "title": "Integer vs. Linear Programming in Python | Towards Data Science",
  "body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\n# Integer vs. Linear Programming in Python\nA guide to identify and solve any optimization problem\n[Maxime Labonne](https://towardsdatascience.com/author/mlabonne/)\nApril 7, 202213 min read\n### Mixed Integer Programming for optimization with Google OR-Tools\n![Image by author, emojis by OpenMoji \\(CC BY-SA 4.0\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/04/161w8yJ9mSDplUK30hXhpQg.jpeg)\nImage by author, emojis by [OpenMoji](https://openmoji.org/) ([CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/))\nWhy is **linear programming** called that way?\nBoth terms are confusing:\n  * **Linear** implies that **nonlinear** programming exists;\n  * **Programming** actually **** means** \"plannin**g\" in this context.\n\n\nIn summary, it has nothing to do with code: linear or not. It's about **optimizing** variables with various constraints.\nIn this article, we're gonna talk about another type of optimization: **integer programming**. We'll see why a good understanding of the problem we face is necessary to choose the right solver. Finally, we will write a model that can take on a bigger challenge and actually solve a whole class of optimization problems.\nLearn this step by step with the interactive [AI Engineer](https://roadmap.sh/ai-engineer) and [Computer Science](https://roadmap.sh/computer-science) roadmaps.\nYou can run the code from this tutorial with the following [**Google Colab notebook**](https://colab.research.google.com/drive/1aIKnXPEiXFo1M3U0EM6arE2teD9KkJdF?usp=sharing).\n![Image by author, emojis by OpenMoji \\(CC BY-SA 4.0\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/04/0Nh7gzKjRzcxFQo_o.png)\nImage by author, emojis by [OpenMoji](https://openmoji.org/) ([CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/))\n## 📊 I. Optimization problem types\nIn the [introduction to linear programming](https://towardsdatascience.com/introduction-to-linear-programming-in-python-9261e7eb44b), we **optimized an army composition**. Here was the result:\ntext\n\n```\n================= Solution =================\nSolved in 87.00 milliseconds in 2 iterations\n\nOptimal power = 1800.0 💪 power\nArmy:\n - 🗡 ️Swordsmen = 6.0000000000000036\n - 🏹 Bowmen = 0.0\n - 🐎 Horsemen = 5.999999999999999\n```\n\nHow can we have 5.999... horsemen? We specified that our variables **should be integers** with `VarInt`. What was wrong with our code?\nThe problem is not the model but the choice of the solver.\nGLOP is a [pure linear programming solver](https://en.wikipedia.org/wiki/GLOP). This means that it **cannot understand the concept of integers**. It is limited to continuous parameters with a linear relationship.\nThis is the difference between **linear** programming (LP) and **integer linear** programming (ILP). In summary, LP solvers can only use real numbers and not integers as variables. So why did we declare our variables as integers if it doesn't take them into account?\nGLOP cannot solve ILP problems, but other solvers can. Actually, a lot of them are **mixed integer linear programming** (MILP, commonly called MIP) solvers. This means that they can consider both **continuous** (real numbers) and **discrete** (integers) variables. A particular case of discrete values is Boolean variables to represent decisions with 0–1 values.\nOther solvers like SCIP or [CBC](https://projects.coin-or.org/Cbc) can solve both **MILP and MINLP** (mixed integer _nonlinear_ programming) problems. Thanks to OR-Tools, we can use the same model and just change the solver to SCIP or CBC.\npython\n\n```\n# Create the linear solver using the CBC backend\nsolver = pywraplp.Solver('Maximize army power', pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)\n\n# 1. Create the variables we want to optimize\nswordsmen = solver.IntVar(0, solver.infinity(), 'swordsmen')\nbowmen = solver.IntVar(0, solver.infinity(), 'bowmen')\nhorsemen = solver.IntVar(0, solver.infinity(), 'horsemen')\n\n# 2. Add constraints for each resource\nsolver.Add(swordsmen*60 + bowmen*80 + horsemen*140 <= 1200)\nsolver.Add(swordsmen*20 + bowmen*10 <= 800)\nsolver.Add(bowmen*40 + horsemen*100 <= 600)\n\n# 3. Maximize the objective function\nsolver.Maximize(swordsmen*70 + bowmen*95 + horsemen*230)\n\n# Solve problem\nstatus = solver.Solve()\n\n# If an optimal solution has been found, print results\nif status == pywraplp.Solver.OPTIMAL:\n  print('================= Solution =================')\n  print(f'Solved in {solver.wall_time():.2f} milliseconds in {solver.iterations()} iterations')\n  print()\n  print(f'Optimal value = {solver.Objective().Value()} 💪 power')\n  print('Army:')\n  print(f' - 🗡 ️Swordsmen = {swordsmen.solution_value()}')\n  print(f' - 🏹 Bowmen = {bowmen.solution_value()}')\n  print(f' - 🐎 Horsemen = {horsemen.solution_value()}')\nelse:\n  print('The solver could not find an optimal solution.')\n```\n\ntext\n\n```\n================= Solution =================\nSolved in 3.00 milliseconds in 0 iterations\n```\n\ntext\n\n```\nOptimal value = 1800.0 💪 power\nArmy: \n - 🗡 ️Swordsmen = 6.0\n - 🏹 Bowmen = 0.0\n - 🐎 Horsemen = 6.0\n```\n\nStrictly speaking, our variables are still floats (`type(swordsmen.solution_value()) = float`) but we can see that they don't have weird decimals anymore: the CBC solver really considered them as **integers**.\nIn this example, we would generally just **round up these values** since the error is insignificant. However, it is important to remember to choose the appropriate solver according to the studied problem:\n  * **LP** for continuous variables;\n  * **MIP/MILP** for a combination of continuous and discrete variables.\n\n\nThere are other types such as **quadratic** (QP) or **nonlinear** (NLP or MINLP, with an exponential objective function or constraints for instance) problems. They're applied in different contexts, but follow the same principles as LP or MIP solvers.\n![Image by author](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/04/1eXPkPpMEX0bNxeRZnuXzKg.png)\nImage by author\n## 🧱 II. Building a general model\nBut what if our **resources change**? Or if the cost of a unit evolved? What if we upgraded horsemen and their power increased?\nOne of the best perks of OR-Tools is that it uses a general-purpose programming language like Python. Instead of static numbers, we can store our parameters in objects like **dictionaries** or **lists**.\nThe code won't be as readable, but it becomes much more flexible: actually, it can be so flexible that we can solve an **entire class of optimization problems** without changing the model (just the parameters).\nLet's transform our input parameters into Python lists and feed them to the solver through a function.\npython\n\n```\n# Inputs\nUNITS = ['🗡 ️Swordsmen', '🏹 Bowmen', '🐎 Horsemen']\n\nDATA = [[60, 20, 0, 70],\n        [80, 10, 40, 95],\n        [140, 0, 100, 230]]\n\nRESOURCES = [1200, 800, 600]\n\ndef solve_army(UNITS, DATA, RESOURCES):\n  # Create the linear solver using the CBC backend\n  solver = pywraplp.Solver('Maximize army power', pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)\n\n  # 1. Create the variables we want to optimize\n  units = [solver.IntVar(0, solver.infinity(), unit) for unit in UNITS]\n\n  # 2. Add constraints for each resource\n  for r, _ in enumerate(RESOURCES):\n    solver.Add(sum(DATA[u][r] * units[u] for u, _ in enumerate(units)) <= RESOURCES[r])\n\n  # 3. Maximize the objective function\n  solver.Maximize(sum(DATA[u][-1] * units[u] for u, _ in enumerate(units)))\n\n  # Solve problem\n  status = solver.Solve()\n\n  # If an optimal solution has been found, print results\n  if status == pywraplp.Solver.OPTIMAL:\n    print('================= Solution =================')\n    print(f'Solved in {solver.wall_time():.2f} milliseconds in {solver.iterations()} iterations')\n    print()\n    print(f'Optimal value = {solver.Objective().Value()} 💪 power')\n    print('Army:')\n    for u, _ in enumerate(units):\n      print(f' - {units[u].name()} = {units[u].solution_value()}')\n  else:\n    print('The solver could not find an optimal solution.')\n\nsolve_army(UNITS, DATA, RESOURCES)\n```\n\ntext\n\n```\n================= Solution =================\nSolved in 2.00 milliseconds in 0 iterations\n```\n\ntext\n\n```\nOptimal value = 1800.0 💪 power \nArmy:\n - 🗡 ️Swordsmen = 6.0\n - 🏹 Bowmen = 0.0\n - 🐎 Horsemen = 6.0\n```\n\nWe obtain the same results: our code seems to work. Now let's **change the parameters** to tackle a slightly more complex problem.\nImagine we have a lot more resources: 🌾 **183000** , 🪵9**0512,** and 🪙80**150,** so we can also produce a lot more units! This is the new table:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/04/1NXG4ze1sme2tqOYLjW6Jyw.png)\nNotice that we transformed the 💪 **powe** r into two values: 💪 **atta** ck and ❤**️healt** h, which is a little more detailed. Health values are higher than attack values, which is why we want to add a weighting factor to make them more comparable.\nLet's take 10 as an example, so _power = 10*attack + health_. Our objective function becomes:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/04/1WGMoYgtG7I7PwJxLAtwSXg.png)\nAdapting our code to this new problem is actually quite simple: we just have to **change the input parameters** and update the **objective function**.\npython\n\n```\nUNITS = [\n    '🗡 ️Swordsmen',\n    '🛡 ️Men-at-arms',\n    '🏹 Bowmen',\n    '❌Crossbowmen',\n    '🔫 Handcannoneers',\n    '🐎 Horsemen',\n    '♞Knights',\n    '🐏 Battering rams',\n    '🎯 Springalds',\n    '🪨Mangonels',\n]\n\nDATA = [\n    [60, 20, 0, 6, 70],\n    [100, 0, 20, 12, 155],\n    [30, 50, 0, 5, 70],\n    [80, 0, 40, 12, 80],\n    [120, 0, 120, 35, 150],\n    [100, 20, 0, 9, 125],\n    [140, 0, 100, 24, 230],\n    [0, 300, 0, 200, 700],\n    [0, 250, 250, 30, 200],\n    [0, 400, 200, 12*3, 240]\n]\n\nRESOURCES = [183000, 90512, 80150]\n\ndef solve_army(UNITS, DATA, RESOURCES):\n  # Create the linear solver using the CBC backend\n  solver = pywraplp.Solver('Maximize army power', pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)\n\n  # 1. Create the variables we want to optimize\n  units = [solver.IntVar(0, solver.infinity(), unit) for unit in UNITS]\n\n  # 2. Add constraints for each resource\n  for r, _ in enumerate(RESOURCES):\n    solver.Add(sum(DATA[u][r] * units[u] for u, _ in enumerate(units)) <= RESOURCES[r])\n\n  # 3. Maximize the new objective function\n  solver.Maximize(sum((10*DATA[u][-2] + DATA[u][-1]) * units[u] for u, _ in enumerate(units)))\n\n  # Solve problem\n  status = solver.Solve()\n\n  # If an optimal solution has been found, print results\n  if status == pywraplp.Solver.OPTIMAL:\n    print('================= Solution =================')\n    print(f'Solved in {solver.wall_time():.2f} milliseconds in {solver.iterations()} iterations')\n    print()\n    print(f'Optimal value = {solver.Objective().Value()} 💪 power')\n    print('Army:')\n    for u, _ in enumerate(units):\n      print(f' - {units[u].name()} = {units[u].solution_value()}')\n  else:\n    print('The solver could not find an optimal solution.')\n\nsolve_army(UNITS, DATA, RESOURCES)\n```\n\ntext\n\n```\n================= Solution =================\nSolved in 74.00 milliseconds in 412 iterations\n```\n\ntext\n\n```\nOptimal value = 1393145.0 💪 power\nArmy:\n - 🗡 ️Swordsmen = 2.0\n - 🛡 ️Men-at-arms = 1283.0\n - 🏹 Bowmen = 3.0\n - ❌Crossbowmen = 0.0\n - 🔫 Handcannoneers = 454.0\n - 🐎 Horsemen = 0.0\n - ♞Knights = 0.0\n - 🐏 Battering rams = 301.0\n - 🎯 Springalds = 0.0\n - 🪨Mangonels = 0.0\n```\n\nThis problem would take a long time for humans to address, but the ILP solver did it in the blink of an eye. Better than that: it also gives us the guarantee that **our solution is optimal** , which means that our enemy cannot find a better army composition for the same cost!\nWe could increase the number of units and give billions of resources but you get the picture: it would just take longer to obtain a solution, but it wouldn't change the problem.\n## ⚔️ III. Combining constraints\nNow, let's say we scouted our enemy and know that their army has a 💪 power of **1,000,00** 0. We could build a much better army, but our resources are precious and it wouldn't be very efficient: all we have to do is to build an army with a **💪 power higher than 1,000,0** 00 (even 1,000,001 would be enough).\nIn other words, the total power is now a **constraint** (💪 > 1,000,000) instead of the objective to maximize. The new goal is to minimize the resources we need to produce this army. However, we can reuse our input parameters since they didn't change.\nThe new constraint can be translated as \"the sum of the power of the selected units must be strictly greater than 1,000,000\".\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/04/1LAq7zYjqG_-njYqOlcdnQQ.png)\nIn code, we can loop through our units and resources to design this constraint.\nThe objective function also has to change. Our goal is to **minimize the sum of resources spent** to build the army.\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/04/1a9PmrsH5Zl2nNWN3LaGG-A.png)\nOnce again, we can loop through our resources to implement it in OR-Tools.\npython\n\n```\ndef solve_army(UNITS, DATA, RESOURCES):\n  # Create the linear solver using the CBC backend\n  solver = pywraplp.Solver('Minimize resource consumption', pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)\n\n  # 1. Create the variables we want to optimize\n  units = [solver.IntVar(0, solver.infinity(), unit) for unit in UNITS]\n\n  # 2. Add power constraint\n  solver.Add(sum((10 * DATA[u][-2] + DATA[u][-1]) * units[u] for u, _ in enumerate(units)) >= 1000001)\n\n  # 3. Minimize the objective function\n  solver.Minimize(sum((DATA[u][0] + DATA[u][1] + DATA[u][2]) * units[u] for u, _ in enumerate(units)))\n\n  # Solve problem\n  status = solver.Solve()\n\n  # If an optimal solution has been found, print results\n  if status == pywraplp.Solver.OPTIMAL:\n    print('================= Solution =================')\n    print(f'Solved in {solver.wall_time():.2f} milliseconds in {solver.iterations()} iterations')\n    print()\n\n    power = sum((10 * DATA[u][-2] + DATA[u][-1]) * units[u].solution_value() for u, _ in enumerate(units))\n    print(f'Optimal value = {solver.Objective().Value()} 🌾  🪵🪙resources')\n    print(f'Power = 💪 {power}')\n    print('Army:')\n    for u, _ in enumerate(units):\n      print(f' - {units[u].name()} = {units[u].solution_value()}')\n    print()\n\n    food = sum((DATA[u][0]) * units[u].solution_value() for u, _ in enumerate(units))\n    wood = sum((DATA[u][1]) * units[u].solution_value() for u, _ in enumerate(units))\n    gold = sum((DATA[u][2]) * units[u].solution_value() for u, _ in enumerate(units))\n    print('Resources:')\n    print(f' - 🌾  Food = {food}')\n    print(f' - 🪵Wood = {wood}')\n    print(f' - 🪙Gold = {gold}')\n  else:\n      print('The solver could not find an optimal solution.')\n\nsolve_army(UNITS, DATA, RESOURCES)\n```\n\ntext\n\n```\n================= Solution =================\nSolved in 4.00 milliseconds in 0 iterations\n```\n\ntext\n\n```\nOptimal value = 111300.0 🌾 🪵🪙resources\nPower = 💪 1001700.0 \nArmy:\n - 🗡 ️Swordsmen = 0.0\n - 🛡 ️Men-at-arms = 0.0\n - 🏹 Bowmen = 0.0\n - ❌Crossbowmen = 0.0\n - 🔫 Handcannoneers = 0.0\n - 🐎 Horsemen = 0.0\n - ♞Knights = 0.0\n - 🐏 Battering rams = 371.0\n - 🎯 Springalds = 0.0\n - 🪨Mangonels = 0.0\n```\n\ntext\n\n```\nResources:\n - 🌾 Food = 0.0\n - 🪵Wood = 111300.0\n - 🪙Gold = 0.0\n```\n\nThe solver found an optimal solution: we need to build **371 🐏 battering ram** s for a total cost of 111,300 🪵wood. Wait, what if we don't have that much wood? In the previous section, we only had 🪵90512: we cannot produce 371 🐏 battering rams. 😱\nSo is it possible to take these **limited resources** into account and still try to **build the best army**? Actually, it's super easy: we just have to copy/paste the constraints from the previous section.\nIn this version, we have two types of constraints:\n  * The total power must be **greater than 1,000,000** ;\n  * We cannot spend more than our **limited resources**.\n\n\npython\n\n```\ndef solve_army(UNITS, DATA, RESOURCES):\n  # Create the linear solver using the CBC backend\n  solver = pywraplp.Solver('Minimize resource consumption', pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)\n\n  # 1. Create the variables we want to optimize\n  units = [solver.IntVar(0, solver.infinity(), unit) for unit in UNITS]\n\n  # 2. Add constraints for each resource\n  for r, _ in enumerate(RESOURCES):\n    solver.Add(sum((10 * DATA[u][-2] + DATA[u][-1]) * units[u] for u, _ in enumerate(units)) >= 1000001)\n\n  # Old constraints for limited resources\n  for r, _ in enumerate(RESOURCES):\n    solver.Add(sum(DATA[u][r] * units[u] for u, _ in enumerate(units)) <= RESOURCES[r])\n\n  # 3. Minimize the objective function\n  solver.Minimize(sum((DATA[u][0] + DATA[u][1] + DATA[u][2]) * units[u] for u, _ in enumerate(units)))\n\n  # Solve problem\n  status = solver.Solve()\n\n  # If an optimal solution has been found, print results\n  if status == pywraplp.Solver.OPTIMAL:\n    print('================= Solution =================')\n    print(f'Solved in {solver.wall_time():.2f} milliseconds in {solver.iterations()} iterations')\n    print()\n\n    power = sum((10 * DATA[u][-2] + DATA[u][-1]) * units[u].solution_value() for u, _ in enumerate(units))\n    print(f'Optimal value = {solver.Objective().Value()} 🌾  🪵🪙resources')\n    print(f'Power = 💪 {power}')\n    print('Army:')\n    for u, _ in enumerate(units):\n      print(f' - {units[u].name()} = {units[u].solution_value()}')\n    print()\n\n    food = sum((DATA[u][0]) * units[u].solution_value() for u, _ in enumerate(units))\n    wood = sum((DATA[u][1]) * units[u].solution_value() for u, _ in enumerate(units))\n    gold = sum((DATA[u][2]) * units[u].solution_value() for u, _ in enumerate(units))\n    print('Resources:')\n    print(f' - 🌾  Food = {food}')\n    print(f' - 🪵Wood = {wood}')\n    print(f' - 🪙Gold = {gold}')\n  else:\n      print('The solver could not find an optimal solution.')\n\nsolve_army(UNITS, DATA, RESOURCES)\n```\n\ntext\n\n```\n================= Solution =================\nSolved in 28.00 milliseconds in 1 iterations\n```\n\ntext\n\n```\nOptimal value = 172100.0 🌾 🪵🪙resources\nPower = 💪 1000105.0\nArmy:\n - 🗡 ️Swordsmen = 1.0\n - 🛡 ️Men-at-arms = 681.0\n - 🏹 Bowmen = 0.0\n - ❌Crossbowmen = 0.0\n - 🔫 Handcannoneers = 0.0\n - 🐎 Horsemen = 0.0\n - ♞Knights = 0.0\n - 🐏 Battering rams = 301.0\n - 🎯 Springalds = 0.0\n - 🪨Mangonels = 0.0 \n```\n\ntext\n\n```\nResources:\n - 🌾 Food = 68160.0\n - 🪵Wood = 90320.0\n - 🪙Gold = 13620.0\n```\n\nSince we now have a **limited resource of 🪵wood,** the number of 🐏 battering rams sadly dropped from 371 to 301. In exchange, we got 681 🛡 ️men-at-arms and 1 lost 🗡 ️swordsman (welcome to them).\nThe total cost of the army is **172,100** , which is much higher than the 111,300 we previously found (+65% increase) but it truly is the optimal solution under these constraints. It shows that we should produce more wood because these 🐏 battering rams are extremely cost-efficient!\nThis example shows **how modular** LP models can be. It is possible to reuse parts of the code, like constraints, in another model to combine them and solve more complex problems.\n## 🧠 IV. Linear Programming vs Machine Learning\nLet's talk about the elephant in the room. Why not use **machine learning** (in a broad sense) instead of linear programming? It's not like this problem cannot be solved with a genetic algorithm for instance.\nMathematical optimization is often neglected in favor of machine learning techniques, but both have their merits:\n  * Linear programming can produce an **optimal solution** in an undetermined amount of time (it can take years), while machine learning can approximate complex functions in no time.\n  * There is **no training** in LP, but an expert is required to build a mathematical model. Machine learning needs data, but the models can be used as black boxes to solve a problem.\n  * As a rule of thumb, problems that **do not have a particular time constraint** and/or are not extremely complex can be advantageously solved with linear programming.\n\n\n![Image by author, emojis by OpenMoji \\(CC BY-SA 4.0\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/04/1CkyNIGyMSguOt1eS9Uh10g.png)\nImage by author, emojis by [OpenMoji](https://openmoji.org/) ([CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/))\n## Conclusion\nIn this tutorial, we dived deeper into our understanding of mathematical optimization.\n  * We talked about solvers and types of optimization problems: **LP, MIP, NLP** ;\n  * We modeled and solved an extremely common optimization problem in an optimal way and **generalized our model** through a function;\n  * We reframed this problem and **merged two sets of constraints** to obtain the best army composition for the lowest price;\n  * We compared the **pros and cons** of linear programming and machine learning.\n\n\nThere are **a lot more problems** where optimization can be applied. For instance, how to create school timetables that satisfy everybody's requirements? How to deliver 1,000 different orders in a minimum amount of time? Where to create a new metro line to maximize its usefulness?\nIn future articles, we'll talk about new types of applications for these techniques, including satisfiability and nonlinear problems.\nI hope you enjoyed this more advanced article. If you like machine learning and optimization, [**let's connect on Twitter**](https://twitter.com/maximelabonne)!\n## Related articles\n> [**Chapter 3: Constraint Programming in Python**](https://towardsdatascience.com/constraint-programming-67ac16fa0c81)\n> [**Part 1: Introduction to Linear Programming in Python**](https://towardsdatascience.com/introduction-to-linear-programming-in-python-9261e7eb44b)\n* * *\n_Learn more about machine learning and support my work with one click - become a Medium member here:_\n> [**Join Medium with my referral link - Maxime Labonne**](https://medium.com/@mlabonne/membership)\n_If you're already a member, you can_[ _follow me on Medium_](https://medium.com/@mlabonne) _._\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](https://assets.insightmediagroup.io/media/1787657499317_sxy3ci.png)\nWritten By\n## [Maxime Labonne](https://towardsdatascience.com/author/mlabonne/)\n[See all from Maxime Labonne](https://towardsdatascience.com/author/mlabonne/)\n[Artificial Intelligence](https://towardsdatascience.com/tag/artificial-intelligence/)[Hands On Tutorials](https://towardsdatascience.com/tag/hands-on-tutorials/)[Linear Programming](https://towardsdatascience.com/tag/linear-programming/)[Programming](https://towardsdatascience.com/tag/programming/)[Python](https://towardsdatascience.com/tag/python/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Finteger-programming-vs-linear-programming-in-python-f1be5bb4e60e%2F&title=Integer%20vs.%20Linear%20Programming%20in%20Python)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Finteger-programming-vs-linear-programming-in-python-f1be5bb4e60e%2F&title=Integer%20vs.%20Linear%20Programming%20in%20Python)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Finteger-programming-vs-linear-programming-in-python-f1be5bb4e60e%2F&text=Integer%20vs.%20Linear%20Programming%20in%20Python)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/11/1wpaIFuwEWBeqZ3So-sERtg-scaled.jpeg)](https://towardsdatascience.com/how-to-make-your-machine-learning-models-more-explainable-f20f75928f37/)\n## [How to make your machine learning models more explainable](https://towardsdatascience.com/how-to-make-your-machine-learning-models-more-explainable-f20f75928f37/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nEspecially when presenting them to a non-technical audience.\n[Amol Mavuduru](https://towardsdatascience.com/author/amolmavuduru/)\nNovember 23, 202011 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/1E6er-WozOCA3yky4y2jXVA.png)](https://towardsdatascience.com/llms-for-everyone-running-langchain-and-a-mistralai-7b-model-in-google-colab-246ca94d7c4d/)\n## [LLMs for Everyone: Running LangChain and a MistralAI 7B Model in Google Colab](https://towardsdatascience.com/llms-for-everyone-running-langchain-and-a-mistralai-7b-model-in-google-colab-246ca94d7c4d/)\n[Large Language Models](https://towardsdatascience.com/category/artificial-intelligence/large-language-models/)\nExperimenting with Large Language Models for free\n[Dmitrii Eliuseev](https://towardsdatascience.com/author/dmitryelj/)\nDecember 5, 202311 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/08/0XmIAjIdxVJ_TQTQa-scaled.jpg)](https://towardsdatascience.com/llmops-serve-a-llama-3-model-with-bentoml-4d580a7a007f/)\n## [LLMOps - Serve a Llama-3 model with BentoML](https://towardsdatascience.com/llmops-serve-a-llama-3-model-with-bentoml-4d580a7a007f/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nQuickly set up LLM APIs with BentoML and Runpod\n[Marcello Politi](https://towardsdatascience.com/author/marcellopoliti/)\nAugust 8, 20245 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/10/0XJYnGEGGB8ZDAzji-scaled.jpg)](https://towardsdatascience.com/apriori-association-rule-mining-explanation-and-python-implementation-290b42afdfc6/)\n## [Apriori: Association Rule Mining In-depth Explanation and Python Implementation](https://towardsdatascience.com/apriori-association-rule-mining-explanation-and-python-implementation-290b42afdfc6/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nAssociation rule mining is a technique to identify underlying relations between different items. There are many methods to perform...\n[Chonyy](https://towardsdatascience.com/author/chonyy/)\nOctober 25, 20206 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/11/0A3mhbsGA8JPSi4Ku-scaled.jpg)](https://towardsdatascience.com/faster-r-cnn-a-step-towards-real-time-object-detection-98c186732a69/)\n## [Faster R-CNN: A Step towards Real-Time object Detection](https://towardsdatascience.com/faster-r-cnn-a-step-towards-real-time-object-detection-98c186732a69/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nFaster R-CNN introduces a novel Region Proposal Network which makes it feasible to achieve real-time performance with the existing...\n[Parth Rajesh Dedhia](https://towardsdatascience.com/author/parthdedhia/)\nNovember 26, 202011 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/05/1TI2lGxJ284DxnPCBFlzllw-scaled.jpeg)](https://towardsdatascience.com/how-to-get-notified-when-your-model-is-done-training-with-knockknock-483a0475f82c/)\n## [How to get notified when your model is done training with knockknock.](https://towardsdatascience.com/how-to-get-notified-when-your-model-is-done-training-with-knockknock-483a0475f82c/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nUsing this Python library to send model training updates. Imagine this scenario - you're working...\n[Amol Mavuduru](https://towardsdatascience.com/author/amolmavuduru/)\nMay 12, 20215 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/11/1otkt-FEt0e3j0T_z53_BMA.png)](https://towardsdatascience.com/a-beginners-guide-to-breaking-into-the-world-of-data-science-28e62301b8da/)\n## [A Beginner's Guide to Breaking Into The World of Data Science](https://towardsdatascience.com/a-beginners-guide-to-breaking-into-the-world-of-data-science-28e62301b8da/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nLearning curriculum and portfolio projects updated for 2023\n[Arunn Thevapalan](https://towardsdatascience.com/author/arunnthevapalan/)\nNovember 15, 20228 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/10/0VTNVFF6p_P5klTY9-scaled.jpg)](https://towardsdatascience.com/my-first-data-science-contest-3f540557decc/)\n## [My first data science contest.](https://towardsdatascience.com/my-first-data-science-contest-3f540557decc/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nFrom knowing nothing to national finalist.\n[Asier Serrano](https://towardsdatascience.com/author/asicoderofficial/)\nOctober 7, 20207 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/08/0qkHKeAwhOvXnBqER-scaled.jpg)](https://towardsdatascience.com/seven-key-features-you-should-know-for-creating-professional-visualizations-with-plotly-f89558de5d0c/)\n## [Seven Key Features You Should Know for Creating Professional Visualizations with Plotly](https://towardsdatascience.com/seven-key-features-you-should-know-for-creating-professional-visualizations-with-plotly-f89558de5d0c/)\n[Data Visualization](https://towardsdatascience.com/category/data-science/data-visualization/)\nCreate Visualizations at the Level of Leading Newspapers\n[Amanda Iglesias Moreno](https://towardsdatascience.com/author/amandaiglesiasmoreno/)\nAugust 6, 20245 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607631/image?etag=1781543525510&width=500&height=500) Critical Mistakes Companies Make When Integrating AI/ML into Their Processes ](https://towardsdatascience.com/critical-mistakes-companies-make-when-integrating-ai-ml-into-their-processes/ \"Critical Mistakes Companies Make When Integrating AI/ML into Their Processes\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ \"How Relevance Models Foreshadowed Transformers for NLP\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n\n\n",
  "metadata": {
    "title": "Integer vs. Linear Programming in Python | Towards Data Science",
    "description": "A guide to identify and solve any optimization problem",
    "keywords": null,
    "author": "Maxime Labonne",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "Integer vs. Linear Programming in Python",
    "og:description": "A guide to identify and solve any optimization problem",
    "og:url": "https://towardsdatascience.com/integer-programming-vs-linear-programming-in-python-f1be5bb4e60e/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2022/04/161w8yJ9mSDplUK30hXhpQg.jpeg",
    "og:image:width": "1280",
    "og:image:height": "720",
    "og:image:type": "image/jpeg",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Maxime Labonne",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "13 min read",
    "article:published_time": "2022-04-07T14:26:32.000Z",
    "article:modified_time": "2022-04-07T14:26:32.000Z",
    "article:author": "https://towardsdatascience.com/author/mlabonne/"
  },
  "paywall": {
    "listed_paid": true,
    "detected": false,
    "marker": "",
    "public_only": true,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 202,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/db450d041200/code/block_000.txt",
      "chars": 217
    },
    {
      "language": "txt",
      "file": "attachments/db450d041200/code/block_001.txt",
      "chars": 1259
    },
    {
      "language": "txt",
      "file": "attachments/db450d041200/code/block_002.txt",
      "chars": 89
    },
    {
      "language": "txt",
      "file": "attachments/db450d041200/code/block_003.txt",
      "chars": 98
    },
    {
      "language": "txt",
      "file": "attachments/db450d041200/code/block_004.txt",
      "chars": 1364
    },
    {
      "language": "txt",
      "file": "attachments/db450d041200/code/block_005.txt",
      "chars": 89
    },
    {
      "language": "txt",
      "file": "attachments/db450d041200/code/block_006.txt",
      "chars": 98
    },
    {
      "language": "txt",
      "file": "attachments/db450d041200/code/block_007.txt",
      "chars": 1741
    },
    {
      "language": "txt",
      "file": "attachments/db450d041200/code/block_008.txt",
      "chars": 92
    },
    {
      "language": "txt",
      "file": "attachments/db450d041200/code/block_009.txt",
      "chars": 265
    },
    {
      "language": "txt",
      "file": "attachments/db450d041200/code/block_010.txt",
      "chars": 1738
    },
    {
      "language": "txt",
      "file": "attachments/db450d041200/code/block_011.txt",
      "chars": 89
    },
    {
      "language": "txt",
      "file": "attachments/db450d041200/code/block_012.txt",
      "chars": 286
    },
    {
      "language": "txt",
      "file": "attachments/db450d041200/code/block_013.txt",
      "chars": 62
    },
    {
      "language": "txt",
      "file": "attachments/db450d041200/code/block_014.txt",
      "chars": 1956
    },
    {
      "language": "txt",
      "file": "attachments/db450d041200/code/block_015.txt",
      "chars": 90
    },
    {
      "language": "txt",
      "file": "attachments/db450d041200/code/block_016.txt",
      "chars": 288
    },
    {
      "language": "txt",
      "file": "attachments/db450d041200/code/block_017.txt",
      "chars": 69
    }
  ],
  "images": [
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2022/04/161w8yJ9mSDplUK30hXhpQg.jpeg",
      "alt": "Image by author, emojis by OpenMoji (CC BY-SA 4.0)",
      "local_path": "attachments/db450d041200/images/000.jpeg",
      "bytes": 140358,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2022/04/0Nh7gzKjRzcxFQo_o.png",
      "alt": "Image by author, emojis by OpenMoji (CC BY-SA 4.0)",
      "local_path": "attachments/db450d041200/images/001.png",
      "bytes": 56889,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2022/04/1eXPkPpMEX0bNxeRZnuXzKg.png",
      "alt": "Image by author",
      "local_path": "attachments/db450d041200/images/002.png",
      "bytes": 406728,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2022/04/1CkyNIGyMSguOt1eS9Uh10g.png",
      "alt": "Image by author, emojis by OpenMoji (CC BY-SA 4.0)",
      "local_path": "attachments/db450d041200/images/003.png",
      "bytes": 53087,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2020/11/1wpaIFuwEWBeqZ3So-sERtg-scaled.jpeg",
      "alt": "",
      "local_path": "attachments/db450d041200/images/004.jpeg",
      "bytes": 475301,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/1E6er-WozOCA3yky4y2jXVA.png",
      "alt": "",
      "local_path": "attachments/db450d041200/images/005.png",
      "bytes": 1772888,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/08/0XmIAjIdxVJ_TQTQa-scaled.jpg",
      "alt": "",
      "local_path": "attachments/db450d041200/images/006.jpg",
      "bytes": 720782,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2020/10/0XJYnGEGGB8ZDAzji-scaled.jpg",
      "alt": "",
      "local_path": "attachments/db450d041200/images/007.jpg",
      "bytes": 535757,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2020/11/0A3mhbsGA8JPSi4Ku-scaled.jpg",
      "alt": "",
      "local_path": "attachments/db450d041200/images/008.jpg",
      "bytes": 506880,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2021/05/1TI2lGxJ284DxnPCBFlzllw-scaled.jpeg",
      "alt": "",
      "local_path": "attachments/db450d041200/images/009.jpeg",
      "bytes": 348669,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2022/11/1otkt-FEt0e3j0T_z53_BMA.png",
      "alt": "",
      "local_path": "attachments/db450d041200/images/010.png",
      "bytes": 1313012,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2020/10/0VTNVFF6p_P5klTY9-scaled.jpg",
      "alt": "",
      "local_path": "attachments/db450d041200/images/011.jpg",
      "bytes": 1352079,
      "downloaded": true
    },
    {
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/08/0qkHKeAwhOvXnBqER-scaled.jpg",
      "alt": "",
      "local_path": "attachments/db450d041200/images/012.jpg",
      "bytes": 490635,
      "downloaded": true
    }
  ],
  "audio": [],
  "videos": [
    {
      "src": "https://www.youtube.com/c/TowardsDataScience",
      "quality": "unavailable",
      "local_path": "",
      "note": "无1080p且无720p，未交付更低清晰度"
    }
  ],
  "links": [
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/latest/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/editors-pick/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/the-variable/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/shipai/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/submissions/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/mlabonne/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/introduction-to-linear-programming-in-python-9261e7eb44b"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/constraint-programming-67ac16fa0c81"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/hands-on-tutorials/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/linear-programming/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/programming/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/python/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/how-to-make-your-machine-learning-models-more-explainable-f20f75928f37/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/amolmavuduru/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/llms-for-everyone-running-langchain-and-a-mistralai-7b-model-in-google-colab-246ca94d7c4d/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/large-language-models/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/dmitryelj/"
    },
    {
      "type": "external",
      "href": "https://write.insightmediagroup.io"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/company/towards-data-science/"
    },
    {
      "type": "external",
      "href": "https://x.com/TDataScience"
    },
    {
      "type": "external",
      "href": "https://openmoji.org/"
    },
    {
      "type": "external",
      "href": "https://creativecommons.org/licenses/by-sa/4.0/"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/ai-engineer"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/computer-science"
    },
    {
      "type": "external",
      "href": "https://colab.research.google.com/drive/1aIKnXPEiXFo1M3U0EM6arE2teD9KkJdF?usp=sharing"
    },
    {
      "type": "external",
      "href": "https://en.wikipedia.org/wiki/GLOP"
    },
    {
      "type": "external",
      "href": "https://projects.coin-or.org/Cbc"
    },
    {
      "type": "external",
      "href": "https://twitter.com/maximelabonne"
    },
    {
      "type": "external",
      "href": "https://medium.com/@mlabonne/membership"
    },
    {
      "type": "external",
      "href": "https://medium.com/@mlabonne"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=Integer+vs.+Linear+Programming+in+Python&u=https%3A%2F%2Ftowardsdatascience.com%2Finteger-programming-vs-linear-programming-in-python-f1be5bb4e60e%2F"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/shareArticle?mini=true&title=Integer+vs.+Linear+Programming+in+Python&url=https%3A%2F%2Ftowardsdatascience.com%2Finteger-programming-vs-linear-programming-in-python-f1be5bb4e60e%2F"
    },
    {
      "type": "external",
      "href": "https://x.com/share?text=Integer+vs.+Linear+Programming+in+Python&url=https%3A%2F%2Ftowardsdatascience.com%2Finteger-programming-vs-linear-programming-in-python-f1be5bb4e60e%2F"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/c/TowardsDataScience"
    },
    {
      "type": "external",
      "href": "https://www.threads.net/@towardsdatascience"
    },
    {
      "type": "external",
      "href": "https://bsky.app/profile/towardsdatascience.com"
    },
    {
      "type": "external",
      "href": "https://thenewstack.io"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-14T11:11:48Z",
  "source_url": "https://towardsdatascience.com/integer-programming-vs-linear-programming-in-python-f1be5bb4e60e/",
  "delivery_status": "excluded_paid",
  "discovery_status": "excluded_paid",
  "missing_reason": "按原约定排除付费/会员全文"
}