{"id":8137,"date":"2023-09-09T08:00:44","date_gmt":"2023-09-09T02:30:44","guid":{"rendered":"https:\/\/tutorpython.com\/?p=8137"},"modified":"2023-10-19T15:14:08","modified_gmt":"2023-10-19T09:44:08","slug":"math-comb-python","status":"publish","type":"post","link":"https:\/\/tutorpython.com\/math-comb-python","title":{"rendered":"math.comb Python"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_80 counter-hierarchy ez-toc-counter ez-toc-transparent ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\"><p class=\"ez-toc-title\" style=\"cursor:inherit\">In This Article<\/p>\n<\/div><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/tutorpython.com\/math-comb-python\/#Understanding_mathcomb_function_in_Python\" >Understanding math.comb function in Python<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/tutorpython.com\/math-comb-python\/#Example_Selecting_playing_cards\" >Example: Selecting playing cards<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/tutorpython.com\/math-comb-python\/#The_Binomial_Expansion_of_xan\" >The Binomial Expansion of (x+a)^n<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/tutorpython.com\/math-comb-python\/#Using_Python_mathcomb_for_binomial_expansion_of_xan\" >Using Python math.comb for binomial expansion of (x+a)^n<\/a><\/li><\/ul><\/nav><\/div>\n<p>To simplify the calculation of combinations, Python provides a library function, <code>math.comb<\/code>, which prevents us from writing complex code. Combinations involve selecting items from a collection without considering the order in which they are chosen.<\/p>\n<p>In this article, we will discuss more about the Python math.com function, and how we could make use of it in another function that carries out binomial expansion.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Understanding_mathcomb_function_in_Python\"><\/span>Understanding <code>math.comb<\/code> function in Python<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>To calculate combinations without writing the code ourselves,\u00a0 Python provides us with the<code>math.comb<\/code> function.<\/p>\n<p><code>math.comb<\/code>\u00a0 function calculates and <strong>returns an integer representing the number of ways we can select items from a collection without bothering about the order in which the items are selected<\/strong>.<\/p>\n<p>Generally, we call math.comb function as follows:<\/p>\n<p><code>math.comb(n, k)<\/code>or:<\/p>\n<pre class=\"language-python line-numbers\"><code>\r\nfrom math import comb\r\n\r\ncomb(n, k)\r\n<\/code><\/pre>\n<p>The parameter <code>n<\/code>is a positive integer representing the size of the collection, and <code>k<\/code> is a positive integer representing the number of items to choose from the collection.<\/p>\n<p>When <code>math.comb<\/code> is called, it returns the number of possible ways to select <code>k<\/code> items from a set having <code>n<\/code> items.<\/p>\n<p>However, we have to note the following behaviors of <code>math.comb<\/code>:<\/p>\n<ol>\n<li><code>math.comb<\/code> will return <code>0<\/code> if <code>k<\/code> is greater than <code>n<\/code><\/li>\n<li>A <code>ValueError<\/code> will be raised if either <code>n<\/code> or <code>k<\/code> (or both) are negative.<\/li>\n<li>A <code>TypeError<\/code> will be raised if either parameter is not an <code>int<\/code><\/li>\n<\/ol>\n<p>The following code snippets show how to make use of Python <code>math.comb<\/code> function.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Example_Selecting_playing_cards\"><\/span>Example: Selecting playing cards<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p><span style=\"font-size: 0.875rem;\">If we had a set of <span class=\"katex-eq\" data-katex-display=\"false\">10<\/span> playing cards, and we wanted to find out the number of different ways we can select <span class=\"katex-eq\" data-katex-display=\"false\">3<\/span> cards from the set.<\/span><\/p>\n<p><span style=\"font-size: 0.875rem;\">We can make use of the following Python code to carry out the calculation.<\/span><\/p>\n<pre class=\"language-python line-numbers\"><code>from math import comb\r\ntotal_num_of_cards = 10\r\nnum_to_select = 3\r\n\r\nresult = comb(total_num_of_cards, num_to_select)\r\n\r\nprint(f\"There are {result} different ways to select {num_to_select} cards from a total of {total_num_of_cards} cards\")\r\n<\/code><\/pre>\n<p><span style=\"font-size: 0.875rem;\">The code snippet effectively makes the function call <code>math.comb(10, 3)<\/code> to get the number of different ways to make the required selection. <\/span><\/p>\n<p><span style=\"font-size: 0.875rem;\">The output is shown below:<\/span><\/p>\n<p><img decoding=\"async\" class=\"aligncenter wp-image-8689 \" src=\"https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_comb_10_3-e1693658679704.png\" alt=\"output of 10 combination 3 using math.comb in python\" width=\"809\" height=\"33\" srcset=\"https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_comb_10_3-e1693658679704.png 784w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_comb_10_3-e1693658679704-300x12.png 300w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_comb_10_3-e1693658679704-768x31.png 768w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_comb_10_3-e1693658679704-600x24.png 600w\" sizes=\"(max-width: 809px) 100vw, 809px\" \/><\/p>\n<p>Now that we have seen how to make use of the <code>math.comb<\/code> function in Python.<\/p>\n<p>We will now look into one application; using math.comb function to calculate binomial coefficients.<\/p>\n<p>First, we will discuss the binomial expansion before diving into its Python implementation.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"The_Binomial_Expansion_of_xan\"><\/span>The Binomial Expansion of <span class=\"katex-eq\" data-katex-display=\"false\">(x+a)^n<\/span><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The binomial expansion allows us to expand a binomial expression raised to a non-negative integer power.<\/p>\n<p>That is, using binomial expansion, we can remove brackets from expressions having the form <span class=\"katex-eq\" data-katex-display=\"false\">(x+a)^n<\/span>, where <span class=\"katex-eq\" data-katex-display=\"false\">n<\/span> is a non-negative integer, and <span class=\"katex-eq\" data-katex-display=\"false\">a<\/span> is a constant, and rewrite it into a polynomial expression.<\/p>\n<p>After expanding <span class=\"katex-eq\" data-katex-display=\"false\">(x+a)^n<\/span>, the coefficients of each term in the resulting polynomial are binomial coefficients.<\/p>\n<p>In other words, each term in the polynomial will have the form <span class=\"katex-eq\" data-katex-display=\"false\">C(n, k)x^{n-k}a^k<\/span>.<\/p>\n<p>The factor <span class=\"katex-eq\" data-katex-display=\"false\">C(n, k)<\/span> is the binomial coefficient, and is calculated using the combination formula <span class=\"katex-eq\" data-katex-display=\"false\">\\frac{n!}{(n-k)!k!}<\/span>. As a result of this connection with Python&#8217;s <code>math.comb<\/code> function, we can easily create functionality to carry out binomial expansion for us.<\/p>\n<p>This will be examined in the next section.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Using_Python_mathcomb_for_binomial_expansion_of_xan\"><\/span>Using Python <code>math.comb<\/code> for binomial expansion of <span class=\"katex-eq\" data-katex-display=\"false\">(x+a)^n<\/span><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>We want to implement a simple function that will take as input the values <span class=\"katex-eq\" data-katex-display=\"false\">a<\/span> and <span class=\"katex-eq\" data-katex-display=\"false\">n<\/span>, and then compute and return the binomial expansion for the specified parameters.<\/p>\n<p>The code is shown below.<\/p>\n<pre class=\"language-python line-numbers\"><code>from math import comb\r\n\r\n# This function converts the input coefficient to a string\r\ndef get_coeff_str(coeff):\r\n    return str(coeff) if coeff&gt;1 else \"\"\r\n\r\n# This function determines the sign of a term\r\ndef get_sign_str(parity):\r\n    return '+' if parity==1 else '-'\r\n\r\n# This function returns the string representation of x raised to power m\r\ndef get_pow_str(m):\r\n    return \"1\" if m==0 else (\"x\" if m==1 else f\"x^{m}\")\r\n\r\n# Main function to expand (x + a)^n\r\ndef expand(a, n):\r\n    terms = []\r\n\r\n    # If a is zero, just return a simple expression for the expansion\r\n    if a==0:\r\n        return get_pow_str(n)\r\n\r\n    # Construct all the terms\r\n    for i in range(n+1):\r\n        # Compute the coefficient for the current term\r\n        coeff = int(abs(comb(n, i)*a**i))\r\n\r\n        # Get the sign for the current term\r\n        parity = int(coeff\/abs(coeff))\r\n\r\n        # Get the power\/index of factor x for the current term        \r\n        idx_x = n-i        \r\n\r\n        # Construct the current term as a tuple\r\n        term = parity, coeff, idx_x\r\n\r\n        # Append the current term to the list of terms\r\n        terms.append(term)\r\n\r\n    # Get the string representation of the first term\r\n    idx_1 = terms[0][2]\r\n    first_term = get_pow_str(idx_1)\r\n    \r\n    # Get the string representation of the remaining terms\r\n    other_terms = \"\".join(\r\n            [\r\n                f\" {get_sign_str(parity)} {get_coeff_str(coeff)}{get_pow_str(idx_x)}\"\r\n                for parity, coeff, idx_x in terms[1:]\r\n            ]\r\n        )\r\n\r\n    # Return the final representation of the expanded binomial\r\n    return first_term + other_terms\r\n<\/code><\/pre>\n<p>Our code contains functions that, together, help produce the string representation of a binomial expansion when given values of <code>a<\/code> and <code>n<\/code>. The main function is <code>expand<\/code> which accepts parameters <code>a<\/code> and <code>n<\/code>, and returns the string representing the expansion <span class=\"katex-eq\" data-katex-display=\"false\">(x+a)^n<\/span>.<\/p>\n<p>The function <code>expand<\/code>checks for the special case <code>a==0<\/code>, which, if it occurs, will just call <code>get_power_str<\/code> to return the\u00a0 <span class=\"katex-eq\" data-katex-display=\"false\">m_{th}<\/span> power of <code>x<\/code>.<\/p>\n<p>If <code>a<\/code> is not zero, it first constructs a list of term objects, each term being represented in memory as a tuple <code>(parity, coeff, idx_x)<\/code>.<\/p>\n<p>Then it constructs the string expression of the final polynomial from the list of term objects.<\/p>\n<p>We can see that while constructing the binomial coefficient for the current term in the <code>for<\/code> loop, it makes use of <code>math.comb<\/code>.<\/p>\n<p>Our code listing has several helper functions to help create the string representation for each term:<\/p>\n<ul>\n<li><code>get_coeff_str(coeff)<\/code>: Returns the string representation for the coefficient <code>coeff<\/code>. It takes care of the special case <code>coeff==1<\/code>, in which case it returns an empty string. With this function in place, we can avoid representations like <code>1x<\/code>or <code>1x^3<\/code>.<\/li>\n<li><code>get_sign_str(parity)<\/code>: Returns the sign for the term. The parity can be <code>1<\/code> or <code>-1<\/code>, which will correspond to <code>+<\/code> or <code>-<\/code> signs respectively.<\/li>\n<li><code>get_power_str(m)<\/code>: Returns the string representation for the <span class=\"katex-eq\" data-katex-display=\"false\">m_{th}<\/span> power of <code>x<\/code>. It takes care of cases like <code>m==0<\/code> (which would lead to representations like <code>x^0<\/code>), and <code>m==1<\/code>(which leads to representations like <code>x^1<\/code>).<\/li>\n<\/ul>\n<p>To test the code, we can use the following lines:<\/p>\n<pre class=\"language-python line-numbers\"><code># Example usage:\r\nprint(f\"(x + 0)^0 = {expand(0, 0)}\")\r\nprint(f\"(x + 0)^3 = {expand(0, 3)}\")\r\nprint(f\"(x + 1)^4 = {expand(1, 4)}\")\r\nprint(f\"(x - 2)^5 = {expand(-2, 5)}\")<\/code><\/pre>\n<p>The following output is displayed:<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter wp-image-8692 size-full\" src=\"https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_binomial_expansion-e1693667752140.png\" alt=\"output expansion of some binomial expressions\" width=\"819\" height=\"75\" srcset=\"https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_binomial_expansion-e1693667752140.png 819w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_binomial_expansion-e1693667752140-300x27.png 300w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_binomial_expansion-e1693667752140-768x70.png 768w, https:\/\/tutorpython.com\/wp-content\/uploads\/2023\/04\/output_binomial_expansion-e1693667752140-600x55.png 600w\" sizes=\"(max-width: 819px) 100vw, 819px\" \/><\/p>\n<p>The output contains cases where <span class=\"katex-eq\" data-katex-display=\"false\">a = 0<\/span> (<span class=\"katex-eq\" data-katex-display=\"false\">(x+0)^0<\/span> and <span class=\"katex-eq\" data-katex-display=\"false\">(x+0)^3<\/span>), and their corresponding expansions.<\/p>\n<p>We can also see sample expansions for <span class=\"katex-eq\" data-katex-display=\"false\">(x + 1)^4<\/span> and <span class=\"katex-eq\" data-katex-display=\"false\">(x + 1)^4<\/span>.<\/p>\n<p>Python <code>math.comb<\/code> proved to be a valuable tool in our small program that creates the string representation for the binomial expansion of <span class=\"katex-eq\" data-katex-display=\"false\">(x + a)^n<\/span>.<\/p>\n<p>This simplified our code, instead of us having to create our own definition for calculating binomial coefficients. With this function provided by Python <code>math<\/code> module, we can write code that implements powerful combinatorial and algebraic capabilities.<\/p>\n<p>We have come to the end of our tutorial. We believe you learned something useful that can help you in your coding journey. Feel free to check out other interesting <a title=\"knowled\" href=\"https:\/\/tutorpython.com\/tutorial\" target=\"_blank\" rel=\"noopener\">Python tutorials<\/a>.<\/p>\n<p>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>To simplify the calculation of combinations, Python provides a library function, math.comb,&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[28],"tags":[],"class_list":["post-8137","post","type-post","status-publish","format-standard","hentry","category-tutorial"],"acf":[],"_links":{"self":[{"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/posts\/8137","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/comments?post=8137"}],"version-history":[{"count":22,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/posts\/8137\/revisions"}],"predecessor-version":[{"id":8713,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/posts\/8137\/revisions\/8713"}],"wp:attachment":[{"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/media?parent=8137"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/categories?post=8137"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/tutorpython.com\/wp-json\/wp\/v2\/tags?post=8137"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}