Posts

Showing posts from April, 2010

Design Pattern in Python

I am exploring some design patters in Python and found some links that might be helpful for you to learn design pattern in Python. Though most of the design patterns are not language specific, but it's nice to see the examples in Python! :) Check the links: Patterns in Python Design Patterns in Python Design Patterns in Python (presentation by Alex Martelli) Video on youtube! Please share if you know about any useful resource / link related to design pattern in Python.

switch-case alternative in Python

Python has so 'switch - case' support unlike most other common languages. Of course you can use If-else block to serve your purpose. But there is an elegant alternative to 'switch-case' in python, using dictionary. Go though the following code (you should try running it). # this is the default function def errorMessage(): print "Incorrect input. Please enter a number between 0 and 3." def fnc0(): print "This is function 0" def fnc1(): print "This is function 1" def fnc2(): print "This is function 2" def fnc3(): print "This is function 3" fncDict = {'0': fnc0, '1': fnc1, '2': fnc2, '3': fnc3} num = raw_input("Enter a number between 0 and 3") # if num is found as a key in the dictionary fncDict, then corresponding function is called # else the function errorMessage is called fncDict.get(num, errorMessage)() Hope you will find it interesting!

Python code to generate random string

Today I wrote a small piece of Python code to generate random string. The string will have only the characters: 0-9, A-Z, a-z. word = '' for i in range(wordLen): word += random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') Here is the complete source code that generates a large file that has a random word one per line. import random def get_random_word(wordLen): word = '' for i in range(wordLen): word += random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') return word def main(): fout = open('word_list.txt', 'w') for i in range(100000000): wordLen = random.randint(5, 15) word = ran_word(wordLen) if i % 500000 == 0: fout.close() fout = open('word_list.txt', 'a') print i fout.write(word+"\n") fout.close() main()