Move the last digit and double the number

Check if you can solve the following:

The objective is to find a number which gets doubled when the last digit of the number is moved to the front of the number.

For an example:

Let abcd is the number, it should get doubled when d which is the last digit, is moved to the front, forming dabc 

2 x abcd = dabc

can you find such a number or few numbers?

First I started building the following equation:

Let x is positive integer and y is a single digit.

x > 0 and 10 > y > 0

therefore, the number can be written as;

2 . (10 . x + y ) = (y . 10^p) + x 

Then,

x = [ (10^p) – 2 ] * [y / 19]

or

y = [19 . x ] / [(10^p) – 2 ]

Then after, it is possible to solve this using trail and error method. It is cumbersome, yet possible. I was tying to figure out a heuristic method to get the answer, but I could not. Therefore I though of using a python script to get the answer.


<pre>#!/usr/bin/python
def eqx(n, y):
    return int(((10**n)-(2))*(y/19))

def eqy(n, x):
    return int((19*x)/((10**n)-2))

def num_conv(num1, num2, p):
    d2 = num1%10
    d1 = int(num1/10)
    if(num2==((d2*10**p)+d1) and (10**p<num1)):
        return True
    return False

for i in range(0,300):
    for j in range(0,10):
        x = eqx(i,j)
        y = eqy(i,x)

        num1 = int((10*x)+y)
        num2 = int((y*(10**i))+x)

        LHS = 2*num1
        RHS = num2
        num_shuffled = num_conv(num1,num2,i)
        if ((LHS==RHS) and (num_shuffled) and (x!=0)):
            print('x,y,p',x,y,i)
            print (format(num1, ',d'),' shifting last digit ',format(num2, ',d'))
            print ('LHS',format(LHS, ',d'), ' RHS',format(RHS, ',d'))
            print('')</pre>

Output:

x,y,p 10526315789473684 2 17
105,263,157,894,736,842 shifting last digit 210,526,315,789,473,684
LHS 210,526,315,789,473,684 RHS 210,526,315,789,473,684

x,y,p 15789473684210526 3 17
157,894,736,842,105,263 shifting last digit 315,789,473,684,210,526
LHS 315,789,473,684,210,526 RHS 315,789,473,684,210,526

x,y,p 21052631578947368 4 17
210,526,315,789,473,684 shifting last digit 421,052,631,578,947,368
LHS 421,052,631,578,947,368 RHS 421,052,631,578,947,368

x,y,p 31578947368421052 6 17
315,789,473,684,210,526 shifting last digit 631,578,947,368,421,052
LHS 631,578,947,368,421,052 RHS 631,578,947,368,421,052

x,y,p 42105263157894736 8 17
421,052,631,578,947,368 shifting last digit 842,105,263,157,894,736
LHS 842,105,263,157,894,736 RHS 842,105,263,157,894,736

Later I found out these kind of numbers are called Parasitic numbers, OEIS sequence of A146088[2][3]. If you are interested, refer to the following Wikipedia article[1] as the starting point.

[1] https://en.wikipedia.org/wiki/Parasitic_number
[2] https://oeis.org/A146088/list
[3] https://oeis.org/A092697

This article is licensed under the Creative Commons Attribution-Share Alike 3.0 Unported (CC BY-SA 3.0) license. 
Advertisements

Solving 6 – 2 + 1 : Think Like Machines?

Recently I have shared the following in my Facebook and it became an interesting discussion. In my next post, I ll post why I have shared it. For the moment will try to solve this !

621

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.

The Birthday Paradox – how to solve using Python

The Birthday Paradox : in a group of random people, how many people should be in the group in order to find at least two people sharing the same birth date? (Not considering February 29th and assuming birthdays are distributed in equal probability.)

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 )

bday_problem

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.

This article is licensed under the Creative Commons Attribution-Share Alike 3.0 Unported (CC BY-SA 3.0) license. 

Planning your future family using Pascal’s triangle

Recently I came across a problem similar to this,

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:

  1. There are n trials
  2. Outcome of each trial is binary (two values, Girl or Boy)
  3. Through out the trials, probability of having a girl or boy is constant.
  4. 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.

Pascal_triangle_small
First 7 rows of 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 nth row of the triangle relates to (x + y)^n.

Lets take having a boy is denoted by x and having a girl is denoted by y. In that case (x + y)^6 would give all the possibilities. However we are interested of having 3 girls and 3 boys. In order to solve that we can take the 6th row of the triangle which is;

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 (x + y)^6 , again it is equal to the sum of numbers in the 6th row.

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

20/64 = 31.25%

Image Credit : user:gunther (wikipedia.org)
This article is licensed under the Creative Commons Attribution-Share Alike 3.0 Unported (CC BY-SA 3.0) license. 

Implementing Roulette Wheel in Python

Fitness Proportionate Selection is a common method in Evolutionary Algorithms, which is also known to us as Roulette Wheel Selection in Evolutionary Algorithms[1] such as Genetic Algorithms.

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])

“all Python codes in this article are released under Creative Commons — Public Domain

#!/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

rws_output

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.

References

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


CC0

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”.

Mixology: Tamarind vodka cocktail

Tamarind is an acidic fruit. The sourness of the fruit is so great and strong which adds an extra uniqueness.  So I though of trying out a cocktail mixture out of Tamarind. This is how it went.

How to prepare Tamarind concentrate

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.

Conceptual Design

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 !

Preparation

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.

Drink No. 1 – Tamarind Concentrate and Vodka

 

Drink No. 2 – Tamarind Concentrate, Cream/ Milk and Vodka

Aromatic

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.

Taste

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.

Fitness

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.

Improvements

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…

Non-Standard rounding function in Python

This post is about a trivial operation which is rounding. Recently I came across a situation where I need to perform a non standard integer rounding. As we know the standard functions available would round the valie to the nearest 10 or its multiplications. My requirement was rounding to the nearest 5.

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.