Simple, right. Can you guess, which is the right answer and the method to achieve the answer?

**I say all three methods could beright and so do 3 and 5 answers. But how?**

Indeed few posted 3 while some posted 5, the correct answer is 5 (considering pure mathematical approach). But what is the correct method. Both methods, two and three are correct. Not sure?

Even though this is a very simple expression, it seems like many were confused with BODMAS or PEMDAS and mathematics.

BODMAS is the UK standard while PEMDAS is the USA version of it. There are few other variations such as BIDMAS, etc.. Apart from the precedence discussed in mathematics, these rules were developed to make the machines (computers, calculators etc) life easier. In order to feed expressions to machines and get a consistent output. Since their inability to think, we direct the thinking pattern using rules.

Forget any method you have followed, BODMAS or PEMDAS whatever. Will get back to our basics.

*6 – 2 + 1 *

Then it is possible to write the expression as follow (without changing it’s original meaning);

*6 + (1 x -2 ) + 1*

Indeed above is equal to

*6 + (-2) + 1*

Can you identify A + B + C there? Then can you remember the **Associative Property**?

**A + B + C = (A + B) + C = A + (B + C )**

Accordingly, do you agree with following?

*6 + (-2) + 1 = 6 + [ (-2) + 1 ] = ( 6 + 1 ) + (-2)*

therefore:

*6 – 2 + 1 = 6 + (-2) + 1 = 6 – 1 = 7 – 2 = 5*

This is why it says + and – are having equal precedence and calculation should be performed left to right. But it is a simplified version, used to teach machines to solve these expressions. Do not get trapped, use the basics always.

Then, how come 3 would be a right answer. If it is mentioned according to BODMAS the answer is 3, then it is incorrect. But if you design a rule as follow A – B + C = A – (B + C) then according to the assumption the answer is 3. If you check my post, you would see I have not mentioned any assumption or method followed. Therefore it should be in pure mathematical form. So here the most suitable or the correct answer would be 5 and the methods are two and three.

This is why we should always follow the method used to solve a problem rather than focusing the answer alone.

Mathematics is a universal language, so why we need to stick to some rules developed to make the life of the machines easier.

]]>

This is the famous Birthday Paradox or the Birthday Problem. In this article, it is discussed how this problem can be build up as an equation and then how to use Python to solve it.

Since an year (not a leap year) has 365 days, it is natural if you think there should be at least 366, so that at least two people share the same birthday. However the answer is surprisingly a smaller value compared to 366.

To solve this problem, following approach can be taken.

If two random people are selected, the probability of not having the same birth date can be calculated as follow:

*P2 = (365/365) x (364/365)*

Therefore the probability of sharing same birth date is *= 1 – P2*

In other words, if a person is selected, his birthday can be an any day of the year which is 365/365. Then in order to have a different birthday the next person’s birthday should fall in any day other than the first person’s birthday, there are only 364 selections, hence the probability is 364/365. So when two persons are considered the probability of not sharing the same birthday can be calculated as mentioned above, P2.

When another person (the third one) is considered, the probability would be 363/365.

If it is generalized (let *n* be the number of people in the group)

*P’n = (365/365) x (365-1/365) x (365-2/365) x (365-3/365) …………………. x {[365-(n-1)]/365}*

The goal is to find n when *Pn* is nearly equal to 0 %, in other words* 1 – Pn* should be nearly equal to 1. Lets take it as .999 or 99.9%

Lets try to simplify the above equation;

*P’n = [(1/365)^n] x { 365 x (365-1) x (365-2) ……………………………….. x [365-(n-1)] }*

*P’n = [(1/365)^n] x {365 x 364 x 363 x …………………………….. 365 -n +1}*

Multiplying with (365 – n)!

*P’n = [(1/365)^n] x {365 x 364 x 363 x …………………………….. 365 -n +1} x [(365 – n)! / (365 – n)!]*

*P’n = 365! / [(365^n) x (365 – n)!]* ———————(Final Equation)

The final equation can be further simplified in permutation notation as follow (as 365! / (365 – n)! = 365Pn )

Now there is a nice equation,

*P’n = 365Pn / 365^n*

Then using the final equation, will try to derive the answer.

#!/usr/bin/python import math as math import sys x = math.factorial(365) ans = 0 disired_probability = 99.9 for i in range (1,366): a = 365**i b = math.factorial(365-i) ans = (1-(x / (a*b)))*100 if (ans > disired_probability): print ('Answer Found - ',i) sys.exit()

The answer is 70.

Therefore, in a group of 70 people, there can be two people sharing the same birth date.

]]>

What if you you are planning for your future family of 3 girls and 3 boys, how difficult it is or is it 50/50 chance?

Need few minutes to think of it? Go for it…

Amidst different methods of solving this problem I decided to use Pascal’s triangle. This is trivial but it was fun, therefore I decided to note it.

The above events distribute along a binomial distribution. Theoretically it satisfies four conditions:

- There are
*n*trials - Outcome of each trial is binary (two values, Girl or Boy)
- Through out the trials, probability of having a girl or boy is constant.
- The trials are independent to each others.

To calculate the coefficients we use Pascal’s triangle. As you all know the rows of the Pascal’s triangle relates to binomial expansion. Check the below Pascal’s triangle.

For example: elements of the 3rd row relates to the coefficient of the binomial expansion of** (x + y)^3 = (x^3 + 3x^2y+ 3xy^2 + y^3) **or in general

Lets take having a boy is denoted by ** x** and having a girl is denoted by

**1 6 15 20 15 6 1**

It can be denoted as follow too:

*1.x^6 + 6.x^5.y + 15.x^4.y^2 + 20.x^3.y^3 + 15.x^2.y^4 + 6.x.y^5 + 1.y^6*

The coefficient of having 3 boys and 3 girls is** 20 ( 20.x^3.y^3)**

How about the total number of events with different combinations? Since there are two outcomes and 6 trials, it should be simply** 2^6 = 64** in other words the sum of all the coefficients of

So the probability of having 3 boys and 3 girls in your future family is

**20/64 = 31.25%**

]]>

The basic idea here is to get a random value out of a sample based on a pre-defined bias.

Following is the python implementation (using numpy library) of the Roulette Wheel selection. The *wheel_vector* should be provided in the following format [….value, bias…..], values can be added as much as required. Bias value is relative, higher the bias value higher the change of getting selected the corresponding value.

For an example, if it is required to declare the wheel vector for a bias dice where no. 6 is more likely to be appeared than other values, it should be defined as follow: note that value 6 is prone to be appeared 5 times more than any other value.

wheel_vector = np.array([1,1,2,1,3,1,4,1,5,1,6,5])

#!/usr/bin/python import numpy as np import random as rand roulette_wheel = np.array((0)) slot_count = 0 def init_roul_wheel(value_array): slot_count = 0 i=0 arrsize = value_array.size while i < arrsize/2: slot_count = slot_count + value_array[2*i+1] i = i + 1 roulette_wheel = np.zeros((slot_count),dtype=np.int) #print(roulette_wheel) i = 0 while i < arrsize/2: rv = value_array[2*i] bv = value_array[2*i+1] j = 0 while j<span data-mce-type="bookmark" id="mce_SELREST_start" data-mce-style="overflow:hidden;line-height:0" style="overflow:hidden;line-height:0" ></span><span data-mce-type="bookmark" id="mce_SELREST_start" data-mce-style="overflow:hidden;line-height:0" style="overflow:hidden;line-height:0" ></span><span data-mce-type="bookmark" id="mce_SELREST_start" data-mce-style="overflow:hidden;line-height:0" style="overflow:hidden;line-height:0" ></span><bv: t = rand.randint(0,slot_count-1) wheel_alloc = roulette_wheel[t] if wheel_alloc == 0: roulette_wheel[t] = rv j = j + 1 i = i + 1 return (roulette_wheel) def spin(rw): slot_count = rw.size randno = rand.randint(0,10000) rot_degree = randno%360 rot_unit = 360/slot_count rol_no = (rot_degree - (rot_degree%(rot_unit)))/rot_unit rol_value = rw[int(rol_no)] return rol_value wheel_vector = np.array([10,1,20,2,30,2,40,4,50,5,60,4,70,3,80,2,90,2]) x = init_roul_wheel(wheel_vector) print (spin(x))

Check how the above code works (online python demo)

The above code is quite lengthy as I purposely omitted shortcuts to slice the arrays hoping that it improves the readability of the code.

The next step is to check if the function is really bias. In order to check that the code has been altered as follow. This version iterates the wheel 1,000,000 times and check the results.

#!/usr/bin/python import numpy as np import random as rand roulette_wheel = np.array((0)) slot_count = 0 def init_roul_wheel(value_array): slot_count = 0 i=0 arrsize = value_array.size while i < arrsize/2: slot_count = slot_count + value_array[2*i+1] i = i + 1 roulette_wheel = np.zeros((slot_count),dtype=np.int) #print(roulette_wheel) i = 0 while i < arrsize/2: rv = value_array[2*i] bv = value_array[2*i+1] j = 0 while j<bv: t = rand.randint(0,slot_count-1) wheel_alloc = roulette_wheel[t] if wheel_alloc == 0: roulette_wheel[t] = rv j = j + 1 i = i + 1 return (roulette_wheel) def spin(rw): slot_count = rw.size randno = rand.randint(0,10000) rot_degree = randno%360 rot_unit = 360/slot_count rol_no = (rot_degree - (rot_degree%(rot_unit)))/rot_unit rol_value = rw[int(rol_no)] return rol_value wheel_vector = np.array([10,1,20,2,30,2,40,4,50,5,60,4,70,3,80,2,90,2]) x = init_roul_wheel(wheel_vector) #print (spin(x)) cal_rounds = 1000000 results = np.zeros((cal_rounds),dtype=np.int); i =0 while i<cal_rounds: value = spin(x) results[i] = value i = i +1 unique, counts = np.unique(results, return_counts=True) print ("RW Vector", wheel_vector, "\n") print ("Roulette Wheel", x) print ("Results: ",unique,"\n\t" ,counts) i = 0 while i<counts.size: #print (unique[i], "occured " + str(counts[i])) precentage = (counts[i]*100)/np.sum(counts) print (unique[i]," precentage - ",str(precentage) + ' %','('+str(round(precentage))+')') i = i +1

Check the output of the code above, it shows number of times the values has been selected and the values have been selected based on the bias (check the percentages). Therefore it can be concluded that the function is working as expected.

[1] Lipowskia, Adam and Lipowskab, Dorota *Roulette-wheel selection via stochastic acceptance* – http://www.sciencedirect.com/science/article/pii/S0378437111009010

To the extent possible under law,

this article, the author

has waived all copyright and related or neighboring rights to “Implementing Roulette Wheel in Python”.

]]>

This is not a difficult task, just get the fruit, peel the outer crust off. Then soak it in water, extract it by hand (use less water to make it more concentrated). Use a porous cloth to strain the juice. Now you have tamarind concentrate.

Awakening the sourness, the acidity of the tamarind juice is my main intention here. However not everyone can bear it, the solution is adding sugar which is not my way. So I thought of softening the sourness with milk. Therefore I added milk instead of sugar. I took White Russian as the inspiration here. So I have two varieties now. Lets try it !

**Ingredients : **

- Tamarind concentrate
- Vodka (used Smirnoff)
- Whipping Cream/ Milk
- Sugar cyrup
- Lime juice
- Pepper

**How to:**

*For the drink no.1,* add 1:1 tamarind concentrate and vodka. Add sugar syrup if you prefer. Fill the shaker with ice and shake well. Strain it and add some lime juice and little bit of Pepper and mix it well. Finally add little Pepper on top of the surface. Serve.

*For the next drink,* The drink no.2, fill the glass with ice cubes. Then add cream and then Tamarind juice on top of it. You may add little bit of milk to get the cloudiness (however this is hard to notice). Stir a bit before serving. I prefer this with no sugar as milk soften the sourness to a manageable limit. But for sugar fans add it to the concentrate and make it ready. Do not add sugar when mixing.

**Garnish**

Salt rim glass would be more suitable. Again sugar for sugar fans.

Fumes of both drinks are rich in sourness of tamarind. Adding some pepper on top of the first drink boosts the vibrant levels. Do not forget to inhale the aroma with care when pepper presents on the surface.

The sourness of tamarind is dominant here. The vodka gets much more soften in presence of tamarind. If you want it to be much stronger consider increasing the vodka portion or add equal amounts of tequila (just a suggestion). If it is unpleasant due to high acidity level consider adding some salt to the tamarind concentrate.

Does not matter the time of the date, the drink no. 1 is indeed a good starting point. Suits well for open-air, under-the-sun events ex: pool party, beach party etc. In summary, if you are looking for a punch or getting ready to start the evening, this would be one of the best choices.

Instead of vodka, try this with tequila base. Or a base like in Long Island which is tequila, vodka, run, gin and triple Sec.

Try it and add your comments…

]]>

So I came across the following solution and I immediately fall in love with this little python snippet and thought of sharing.

Here is goes.

#!/usr/bin/python def floor(value, divisor): ans = value%divisor return value-ans def ceiling(value, divisor): ans = value%divisor return value+divisor-ans a = 105 x = ceiling(a,5) y = floor(a,5) print(x) print(y)

The ceiling ( ) function round the value to the nearest upper value which is a multiplication of 5. The floor ( ) function would round the value to the nearest lower value which is a multiplication of 5.

]]>

Instead of PHPSecLib, openSSL can be used to implement RSA cryptography functions in PHP as well.

The major drawback in Symmetric-Key Encryption is the usage of the same key to encrypt and decrypt data. However unlike in Asymmetric-Key encryption (I would say RSA hereafter) there is no limit on the data size that can be encrypted and it is relatively faster than RSA. As a result RSA is used to exchange Symmetric Keys securely and then the client and the server continues to communicate based on symmetric-key encryption. Not only for communication but also we can use symmetric key encryption in data storage too. For an example before storing data on a database, it is a good practice to encrypt those data, in such a scenario symmetric key encryption is much more suitable than RSA.

There are plenty of other libraries which provide symmetric key encryption, however it is recommended to use libraries like openSSL or PHPSecLib as they are extensively tested and well maintained. My advice is to use openSSL as much as possible, however due to limitations on your server, it may not be possible to use openSSL for RSA but it can always be used for symmetric key encryption.

Will check the PHP code for the task. It is simple !

My PHP version is PHP Version 7.0.10 and using OpenSSL/1.0.2h, if you want to check yours you can use phpinfo(); function which gives all information regarding your PHP installation.

<?PHP $text = 'This is a secret message that should be encrypted before saving it to the database so that even the database is compromised the attacker wont be able to steal data'; $encryption_key = 'password'; $iv = 'randomdigit16bit'; $encrypted_data = openssl_encrypt($text, 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, $iv); $encrypted_data = base64_encode($encrypted_data); var_dump($encrypted_data); ?>

The code is self explaining, openssl_encrypt is the function that should be used and $text is the data that should be encrypted, then the next parameter is the cipher method, $encryption_key is the key to decrypt the encrypted text. This needs to be stored as it is required later to decrypt the data. I ll discuss about storing keys securely in a future blog post, as it is quite out of the scope for this topic.

Decryption is to be carried out as follow:

<?PHP $text = 'This is a secret message that should be encrypted before saving it to the database so that even the database is compromised the attacker wont be able to steal data'; $encryption_key = 'password'; $iv = 'randomdigit16bit'; $encrypted_data = openssl_encrypt($text, 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, $iv); //$encrypted_data = base64_encode($encrypted_data); $decrypted_data = openssl_decrypt($encrypted_data, 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, $iv); var_dump($decrypted_data); ?>

Same as the openssl_encrypt function openssl_decrypt function could be used. Note that same $encryption_key and the $iv have been used.

Same as the $encryption_key, $iv should be same in encryption and decryption. $iv is known as the Initialization Vector which adds an extra layer of protection. It can be a random 16 bits string and the value should be stored as it requires in the decryption process as same as the encryption key.

The role of the $iv (Initialization Vector) is to differentiate the encrypted text. For an example the encryption key could be common per user or your web site etc. But you can use a random $iv per each encryption. As a result if you encrypt the same value using the same key, the result is going to be different when you use two different $iv.

Following method can be used to generate 16 bits IV. Make sure you store the IV otherwise decrypted data will not be able to decrypt back.

$iv = openssl_random_pseudo_bytes (16);

That is it, simple and handy isnt it?

]]>

For an example, it is possible to order letters A B C D into 24 words. General form is n!. Since there are 4 distinct letters number of ways are 4! which is 24. But what if there are identical objects. For an example lets say we need to order following letters, A B B C D, note that there are 2 Bs.

Such situations are termed as “Permutations with Repetitions”.

Taking the above example of 5 letters, A B B C D. If the letters were distinct then there should be 5! ways of ordering them. But as it got 2 Bs the number of ways should get reduced, because it doesn’t really matter which B comes first and which B comes next. Both are identical. As a result we need to filter-out such occurrences.

In order to achieve the correct result, the total number of permutations which is 5! should be divided by the number of ways that the identical objects can be arranged. In this case it is 2Bs, 2!. So the answer is 5!/2!

**Lets see how the word “R E F E R E N C E” can be written in different ways.**

Note that it has 9 letters. R is repeated twice, E is repeated four-times. Therefore if there were no identical letters then number of ways are 9!. But since there are 2 Rs and 4 Es, 9! should be divided by the number of ways that the identical letters can be arranges which is 2! for R and 4! for E. So the number of ways are 9! / (2! 4!) = 7560

**Lets see how following digits can be arranged 2, 2, 2, 7, 7, 8, 8, 8, 9**

There are three 2s, two 7s, three 8s and one 9. Again 9 digits therefore total number of ways are 9!, but it should be divided by the repeating digits. Therefore the total number of ways are 9!/(3! 2! 3!) = 5040

Sometimes we need to order objects, first selecting them from a pool of objects and then arrange them in an order. Lets assume we are given 4 distinct letters and we need to group them and create two letter words. Then we have total number of ways of 4! / (4-2)! = 12

It can be termed as **nPr = n! / (n-r)!**, where the n is the pool size and the r is the number of objects that can be selected.

If there are identical objects them as we did early we need to divide the total number of ways from the number of ways that he identical objects can be arranged.

**If the object pool is “A B B C C C D E”, how many ways are there to construct 4 letter words out of them?**

Since there are 8 letters in the pool and as we get 4 letters out of it, total number of arrangements are 8! / (8 – 4) ! = 1680

Then as there are identical objects, 2Bs and 3Cs, total number of ways 1680 / (2! 3!) = 140

In other words: 8 ! / {(8 -4)! * 2! * 3!} = 140

**If you are interested consider taking up following quizzes:**

Some worked-out examples

http://www.vitutor.com/statistics/combinatorics/permutations_repetition.html

Calculator

http://www.dcode.fr/permutations-with-repetitions

]]>

I prefer using NumPy library for handling arrays in real-time python developments. However it is required to have a basic knowledge of handling arrays in Python first.

List is a data structure that holds values of any type. It can be a collection of strings, integers or any other valid data type in python. They are dynamic (known as mutable too), meaning that you can add or delete values as you wish.

Define a List with [ ]

It is quite same as other languages, you can use [ ] to define a list.

newArray = []

or with values

newArray = ["Population","X","size",200,"size"]

As in arrays, the element counts starts from 0 and you can use “slicing” in Lists too.

print (newArray[2])

you may use the slicing to assign values to a List elements too.

newArray[2] = 100

You may notice that you can assign a new value and it can be in a different type.

Following is a python script showing things we discussed so far

#!/usr/bin/python newArray = ["Population","X","size",200,"size"] print (newArray) print ("Property of X = " + newArray[2]) newArray[3] = 200/3.5 print (newArray)

It is possible to define multi dimensional lists and they behave quite similar to multidimensional arrays.

newArray = ["POST",["Status Code",100,200,300],["fail","pass","error"]]

you can use any combination of data types and any number of dimensions. Again slicing can be used to retrieve or assign values as we have observed above. Refer to the example code below:

#!/usr/bin/python newArray = ["POST",["Status Code",100,200,300],["fail","pass","error"]] print (newArray[1][2]) newArray[2][1] = "Success" print (newArray)

However our goal in this post is to see how associative arrays can be handled in Python. In Python associated arrays are termed as dictionaries. Simply it is ordered key-value pairs.

How to define a dictionary:

dataArray = {"method":"POST", "action":"file.py", "status": 500}

So that later you can use the key value to retrieve the value of the element.

dataArray["action"]

It is possible to use dict(sequence) function to create a dictionary too.

seq = (("method","POST"), ("action","file.py"), (2,500))

dataArray = dict(seq)

Values can be altered referring to the key value

seq = (("method","POST"), ("action","file.py"), (2,500)) dataArray = dict(seq) dataArray[2] = 100 print (dataArray)

To delete an element, del(element) statement can be used.

seq = (("method","POST"), ("action","file.py"), (2,500))<span data-mce-type="bookmark" id="mce_SELREST_start" data-mce-style="overflow:hidden;line-height:0" style="overflow:hidden;line-height:0" ></span> dataArray = dict(seq) del(dataArray["action"]) print (dataArray)

List data type has more methods that are very useful, will cover them briefly.

*list.count(x)* – Return the number of times value x appears in the list.

*list.append(x)* – Add element x to the list

*list.extend(newList)* – Extend the list by appending all the items in the newList

*list.insert(n, x)* – Insert the element x at n position. The current element at the position n will be moved backward.

*list.remove(x)* – Remove element which is the first item having the value x

*list.pop([i])* – i is optional, remove the element in position i

*list.index(x)* – Return the index of the first element whose value is x in the list.

*list.reverse()* – Reverse the elements of a list

In the next part of the post will check how to implement basic data-structures such as stack and queue in python using lists.

Stack is analogous to a pile of books. The elements which goes last comes first. Therefore stack is a list where the index 0 of the list is the first element of the stack (this element will be the last element to be taken out).

#!/usr/bin/python stack = [1, 2, 3, 4] #add elements to the stack stack.append(5) stack.append(6) print(stack) #taking elements out x = stack.pop() print(x)

Not like stacks, in queues element which goes first come out first. Therefore it is possible to use pop() to retrieve values from a queue but when appending elements it should be placed at the beginning of the list. That is quite inefficient in lists as whole list should be shifted right to accommodate space to the new element.

It is recommended to use collections.deque in python for this purpose which is much more efficient.

However in this post will see how queues can be implemented using the knowledge we have gained so far.

#!/usr/bin/python queue = [4,3,2,1] value = [5] value.extend(queue) queue = value print (queue)

Note that in the above example, the new value has been define as an element having one element. Otherwise it is not possible to use this technique.

Following is another way:

#!/usr/bin/python queue = [4,3,2,1] queue.reverse() queue.append(5) queue.reverse() print (queue)

Both techniques have 4 lines but I guess that the first method should be more efficient.

Will write on NumPy in the next post.

]]>

We live this one routing of a day for 75 years and we call it life, no that is not life. If you are still thinking why you have been sent here, if you are still juggling with the concept why you are here, you have not lived yet. You work hard, you make money , you do it for your self. that is not life.

You go out, seek for people who need your help, you make their lives better, you become that sponge which can absorb all the negativity and you become that person who can emit beautiful positive vibes, and when you realize you have changed someone’s life and because of you, this person didn’t give up that is the day when you live.

]]>