Wednesday, August 15, 2012

Choose random elements from a list.

Hi! there exists a simple library function that can be found in the random module to sample out a list of length N which contains the random elements from a given list. The original list remains unchanged.

Here is the simple code snippet.

import random

old_list = [1,2,3,4,5]
new_list = random.sample(old_list, 3)

Running the above code will give us a list of length 3 containing random elements from old_list.
O/P:
>>> random.sample(a, 3)
[5, 1, 2]
>>> random.sample(a, 3)
[1, 5, 2]
>>> random.sample(a, 3)
[1, 2, 5]
>>> random.sample(a, 3)
[2, 1, 5]
>>> random.sample(a, 3)
[5, 1, 3]
>>> random.sample(a, 3)
[1, 3, 2]


*Note: If the old_list contains repeated elements then its not guaranteed to have unique element in the new_list.

Reference: http://docs.python.org/library/random.html

Sunday, August 12, 2012

Using VIM: Multiline comments.

Hi,

If you use VIM for code editing and finding it difficult to comment multiple line at a time then here is the simple process to do so:
1. Enter Visual mode(Block mode) using ctrl+v, select the lines which you want to comment.
2. Then do, I#<Esc>

Wednesday, August 8, 2012

Password Generator In Python

Here is my small code fragment to generate random alphanumeric password for given length.

def generate_random_password(length=10):
        """
        This function will generate the random alphanumeric password of given  length.
        param length: The requied password length.

        rtype: a string containing the generated password.
        """
        letters = string.letters
        digits = string.digits
        message = letters + digits
        passwd = ''
        for i in range(length):
            passwd += random.choice(message)
        return passwd


You can call above function with the following arguments:
generate_random_password()
generate_random_password(5)
generate_random_password(length=15)

The above function can be enhanced by adding special character support etc.

Have fun :)