Generate integer from 1 to 7 with equal probability using program in Python
Introduction: We usually write programs without even think about probability. Well, you can also write those programs by calculating the probability distribution function. This probability distribution function can be calculated with the help of given numbers and their frequencies. The below example shows this very well where we are using a quite technique to do this.
First of all, let us go through the coding part.
#an empty function which does nothing just return 0 def emp(): return 0 #A function that uses emp() function for generate number def main_fun(): j = 0 #j is the variable which keeps the number multiple of 5 it is just a refrence j = (3 * emp()) + (emp() - 3) # because 7*2 =14 so we are cheaking for everynumber that it should be below 21 if (j < 14): if(j < 0): return (j % 7 ) + 1 else: return (j % 7) + 1 return main_fun() print(main_fun());
The first function is an empty function which returns 0, then comes the second part where we are making a function main_fun which will print a number, Let us see how that function is working.
First of all, we are declaring a number j = 0, then we are applying a mathematical operation which keeps 1 to 9 numbers in j you can understand this by this simple code:
for i in range(1, 6): for j in range(1,6): print(3* i + j-3)
Output: 1 2 3 4 5 6………………………17
As we are using only one loop there we will generate 1 to 9 numbers now the nearest number which is multiple of 7 is 14 so we need to check j should be small from it or not. You can even write 7 there and check but because we are checking till 7 here so I am checking with 14, you can go for even 21 or 49. Now after checking with 14, we need to manipulate the results so, we are just adding 1 there. And it is done.