Archive for the ‘Python’ Category

While i was working on the project onspot_v2, i came across with a specific need. onspot_v2 makes use of the django admin interface for data entry. When employees are entering data, ‘branch’ field in the form will get populated automatically as per the branch of the employee. When a manager is entering data using the form, an extra field should appear to select the ‘branch’ instead of automatically populating. Googling didn’t help much. Finally i thought of overriding the ModelAdmin.add_view() method which is invoked when you try to add an entry using the admin. I changed the editable property of the field ‘branch’ inside after checking the request.user and it worked out. Part of my code in admin.py

from django.contrib import admin
from books.models import Agent, PolicyIssue

class PolicyIssueAdmin(admin.ModelAdmin):
    def add_view(self, request, form_url='', extra_context=None):
        if request.user.get_profile().is_employee:
            self.model.branch.field.editable = False
            self.model.branch.field.editable = True
        return super(PolicyIssueAdmin, self).add_view(request, form_url)

admin.site.register(PolicyIssue, PolicyIssueAdmin)

Read Full Post »

Here is a python script to find solution for a jumbled word. Give a jumbled word as parameter, it will list the possible solutions.

import sys

dictfile = "/usr/share/dict/cracklib-small"

def get_words(text):
	""" Return a list of dict words """
	return text.split()

def get_possible_words(words,jword):
	""" Return a list of possible solutions """
	possible_words = []
	jword_length = len(jword)
	for word in words:
		jumbled_word = jword
		if len(word) == jword_length:
			letters = list(word)
			for letter in letters:
				if jumbled_word.find(letter) != -1:
					jumbled_word = jumbled_word.replace(letter,'',1)
			if not jumbled_word:
	return possible_words		
if __name__ == '__main__':
	words = get_words(file(dictfile).read())
	if len(sys.argv) != 2:
		print "python %s <jumbled word>" % sys.argv[0]
	jumbled_word = sys.argv[1]
	words = get_possible_words(words,jumbled_word)
	print "possible words :"
	print '\n'.join(words)

Don’t forget to change the ‘dictfile’ to the wordslist file you have in your system.

Here is the screenshot of script output.

Read Full Post »

Actually this is a sample question appeared in codejam contest conducted by mobme wireless. Imdbpy python module is used to retrieve movie informations from imdb.

For those who don’t know about this event : http://codejam.mobme.in/

Sample Question :

Write a program that ranks Hollywood actors based on the number of their appearances in a list of top 100 movies. There are a number of top movie lists on the Internet and it’s up to you to choose one. We’d prefer you choose one that has an open API.

Solution in Python :

#!/usr/bin/env python

__author__ = "Rag Sagar.V"
__email__ = '@'.join(['ragsagar','.'.join([_ for _ in ['gmail','com']])])

from twisted.internet import reactor, threads
import re,imdb,itertools

actors_rating = {} #actors_rating['actor name'] = rank
rank = 0
count = 1
current_rank = 0
concurrent = 5
finished = itertools.count(1)

	imdb_access = imdb.IMDb()
except imdb.IMDbError, err:
	print err
top_100 = imdb_access.get_top250_movies()[:100]

def populate_actors(mid):
	movie = imdb_access.get_movie(int(mid))
	#print movie
	for i in (0,1):
		actor_name =  movie['cast'][i]['name']
		if actors_rating.has_key(actor_name):
			actors_rating[actor_name] = actors_rating[actor_name] + 1
			actors_rating[actor_name] = 1
	if finished.next()==added:
added = 0
for movie in top_100:
	added += 1	
	req = threads.deferToThread(populate_actors, movie.getID())

except KeyboardInterrupt:

for actor in sorted(actors_rating, key=actors_rating.get, reverse=True):
	previous_rank = current_rank
	current_rank = actors_rating[actor]
	if previous_rank !=  current_rank :
		rank += count
		count = 1
		count += 1	
	print rank,actor   

Dependency :

Read Full Post »

Older Posts »

%d bloggers like this: