Permutations with Repetition

Permutation is all about ordering objects in certain ways.

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

Selecting and Arranging

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




Handling arrays (lists) in Python

Arrays are one of the fundamentals in any programming language. However if you have used Python; for example, you may not find arrays in it. Instead you get list. It is a more general form of an array.

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

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

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

m-D List

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:

newArray = ["POST",["Status Code",100,200,300],["fail","pass","error"]]
print (newArray[1][2])
newArray[2][1] = "Success"
print (newArray)

Associative Arrays in Python

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":"", "status": 500}

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


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

seq = (("method","POST"), ("action",""), (2,500))

dataArray = dict(seq)

Values can be altered referring to the key value

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

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

seq = (("method","POST"), ("action",""), (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)
print (dataArray)

Methods on List

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

stack = [1, 2, 3, 4]
#add elements to the stack
#taking elements out
x = stack.pop()


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.

queue = [4,3,2,1]
value = [5]
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:

queue = [4,3,2,1]
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.

Have you lived yet?

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.

Overcoming the conventional stumbling block to global success

I do hope you will enjoy the following article as much as I did. May it be a motivation …

Dr. Sanjiva will be delivering “The IESL Ray Wijewardene Memorial Lecture – Nobody to Leader : Achieving Global Leadership with Software”, today (2017 Sep 7) at IESL. More Info…

a 22-year-old, ftesh out of university, can solve problrms but they haven’t seen many problems yet. You learn problems as yoh go along. The key to being a good entrepreneur is not about identifing problems but about caring enough to solve it.

Copyright Notice : This article appeared in DailyFT paper, 2017 Sep 6. and I hold no copyrights. Shared with an intention to educate others. All rights reserved by the above named publication.

How to include PHPSecLib

I got an interesting question on my blog post, RSA cryptography in PHP (How To?). Even the example, I have provided works fine with the source I have provided, you would probably get into some issues when trying it from the scratch. Including PHPSecLib is not straight forward. You cannot just use include() or include_once() functions directly. It follows PEAR standard (PHP Extension and Application Repository), therefore you need to use the following trick if you dont have PEAR installed in your server or in your LAMP/ WAMP deployment.

For an example consider following directory structure:

------- App
+ ----------------- Core
+ ----------------- Vendors

Assuming that your code lies in the “Core” directory, and you are planning to place PHPSecLib in the “Vendors” directory, you can include the following to your code so that it will find the PHPSecLib without no issue:

$path = '../vendors/phpseclib/'; 
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

Working example:


$path = '../vendors/phpseclib/';
	set_include_path(get_include_path() . PATH_SEPARATOR . $path);

$rsa = new Crypt_RSA();
$keys = $rsa->createKey(2048);


$rsa->loadKey($keys['publickey']); // public key
$plaintext = 'I want to get encrypted !';

$ciphertext = $rsa->encrypt($plaintext);


$rsa->loadKey($keys['privatekey']); // private key
$text = $rsa->decrypt($ciphertext);

Note that we have explicitly defined the path for the library from the current directory where the executing script is located.

If you insist on using autoload instead, it can be achieved in the following manner. You cannot straight away let the autoload find the class as the file name and the class name are different. Therefore we need to change the path as the code can locate the Crypt_RSA class, which is ../vendors/phpseclib/Crypt/RSA.php


spl_autoload_register(function ($class_name) {
	$path = '../vendors/phpseclib/';
	set_include_path(get_include_path() . PATH_SEPARATOR . $path);
	include_once $class_name.'.php';

$rsa = new Crypt_RSA();
$keys = $rsa->createKey(2048);


$rsa->loadKey($keys['publickey']); // public key
$plaintext = 'I want to get encrypted !';

$ciphertext = $rsa->encrypt($plaintext);


$rsa->loadKey($keys['privatekey']); // private key
$text = $rsa->decrypt($ciphertext);

Hope you will find this information useful. Cheers !!

How to store keys (RSA) ?

The last post was about handling RSA cryptosystem in PHP. This post is covering a small aspect of the last post.

Once keys (Public and Private) are generated there should be a method of storing the keys, both private and the public keys to use later. Since the keys are having a specific format you are not able to store them in a raw format. It doesn’t work the next time when you try to use them.

There are few formats and methods we can use. In the last post, the generated keys are in PEM (Privacy Enhanced Mail) format. Dont get confused with that. I am suggesting a technique to store the keys. There are many other ways to get this accomplished. Among them base64 encoding/ decoding would be quite handy and easy.

PEM formatted private key is noted below.

Proc-Type: 4,ENCRYPTED


Base64 encoded key (note that it appears as a single line, no line breaks).


You can simply use a “TEXT data typed” filed in MySQL table to store base64 encoded key pair and then when it is needed just base64 decode and use it. Even you can apply further encryption against the base64_encoded string to make the key much more secure. You can hash the base64_encoded string and create signatures of the keys as another security measurement.

Simply use the base64_encode( ) and base64_decode( ) functions in PHP.

$encoded_key = base64_encode(myRSA::$privateKey);

$private_key = base64_decode($encoded_key);

NOTE: base64 encoding doesn’t provide any additional security, it is purely assisting towards storing/ passing the keys in a more comfortable way. Therefore you need to use an additional security layer (eg: database data encryption) on top of the stored keys to make it much more secure.

RSA cryptography in PHP (How To?)

Being security is one of the utmost considerations in current web site/ application development process, I am sure you have spent a lot of time writing codes to handle encryption in your applications.

In this article I am trying to present one of my favorite ways to solve this issue, the RSA encryption/ decryption handling in your PHP development.

This is quite straight forward as I am using PHPSecLib package. I was using openSSL library for PHP for few years and recently started dealing with this package. It is pretty cool implementation so I started loving it.

First of all you need to get the package, it is available to download[1] and it comes with MIT license[2], GPL compatible[3].

If your intention is to use PHPSecLib only for RSA encryption and decryption I suggest including only two directories which are Crypt and Math in your production environment.

First step towards the RSA encryption is to create the public and private keys. Note that I have secured the keys with a passphrase.

$rsa = new Crypt_RSA();

echo $keys['privatekey'];
echo $keys['publickey'];

The code is self explaining. createKey() method is taking the bit value of the key and output an array which contains the Private and Public keys. setPassword() is optional, you can omit it if you dont want to create the keys with a passphrase. If you want to use 2048 bit key then provide 2048 as an argument in createKey() instead 1024.

Once keys are ready you can start the encryption. I am using using the public key. Passphrase is not required when encrypting.

$plaintext = 'Text to be transmitted securely !!!';
$ciphertext = $rsa->encrypt($plaintext);
echo $ciphertext;

Decryption goes as follow (using the private key), note that the passphrase is mandatory:

$re_plaintText =  $rsa->decrypt($ciphertext);
echo $re_plaintText;

I have written a static class to demonstrate how encryption can be carried out. Please check the following:

***DO NOT use this code in your production env as the code lacks lot of fine tuning and security measures***

This is just to illustrate how the PHPSecLib can be used in a code



class myRSA
	public static $privateKey = '';
	public static $publicKey = '';
	public static $keyPhrase = '';
	public static function createKeyPair()
		$rsa = new Crypt_RSA();
		$password = base64_encode(sha1(time().rand(100000,999999)));
		$rsa->setPassword($password );

	public static function encryptText($text)
		$rsa = new Crypt_RSA();
		$encryptedText = $rsa->encrypt($text);
		return $encryptedText;

	public static function decryptText($encryText)
		$rsa = new Crypt_RSA();
		$plaintext = $rsa->decrypt($encryText);
		return $plaintext;


//create keys

//Text to encrypt
$text = "A secret lies here, send the text via a secure mode";
echo 'Text : '.$text;

$secureText = myRSA::encryptText($text);
echo 'Encrypted : '.$secureText;

$decrypted_text =  myRSA::decryptText($secureText);
echo 'Decrypted Text : '.$decrypted_text;

PHPSecLib API Documentation is available here.[4] A handy reference to check when you get stuck or need more info on methods.