Permutations and Combinations
If you are a 12th grader like me, you would surely agree that the chapter 'Permutations and Combinations' of Mathematics is easily one of the most heinous chapters. It has straightforward formulas for permutations and combinations, but it is the calculation that gets to us.
Generally questions from this chapter are pretty easy if you get the logic, but sometimes the expression involves pretty large numbers and it can get messy. Now, that is something your normal calculator can do, can it? So lets leave that for our pet Python.
The Code
This is a very simple program with just the logic, but I shall explain the code part by part. Skip to the end if you would like to download the python file. No strings attached.
Ok, so I'd like the code to run as long as I want in the command prompt. Inputting the expression as exp, we take an empty list to store each digit of the expression so as to seperate the numbers from the letter:
the variable exp_pace stores the index of the letter in the inputted expression. left_num and right_num are respectively the n and r in the expression nCr or nPr. Note that even though left_num and right_num are integers, they are of type string. nature is storing the type of expression for use of formula.
So we run two for loops to get the n and r and convert them to type int. Going ahead is the formula. Instead of just telling python to keep multiplying the numerator as well as denominator by a number 1 less than the previous number (factorial), we tell it to multiply till it reaches the number equal to (n-r), which will get cancelled. Then the division of r! depends on whether we are calculating for permutation or combination.
So that was that. We now have a small program that will instantly give value of the permutation or combination no matter how big it is.
Comments
Post a Comment