Feeds:
Posts
Comments

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:
				possible_words.append(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]
		sys.exit()
	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.

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)
reactor.suggestThreadPoolSize(concurrent)


try:
	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
		else:
			actors_rating[actor_name] = 1
	if finished.next()==added:
		reactor.stop()
	
added = 0
for movie in top_100:
	added += 1	
	req = threads.deferToThread(populate_actors, movie.getID())

try:
	reactor.run()
except KeyboardInterrupt:
	reactor.stop()	

   
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
	else:
		count += 1	
	print rank,actor   
    
    

Dependency :
imdbpy

Here is a python script to wish you Good Morning or Good Evening according to the time of the day.

#!/usr/bin/python
import time

current_hour = time.strptime(time.ctime(time.time())).tm_hour

if current_hour < 12 :
	print "Good Morning!"
elif current_hour == 12 :
	print "Good Noon!"
elif current_hour > 12 and current_hour < 18 :
	print "Good AfterNoon!"
elif current_hour >= 18 :
	print "Good Evening!"

Now if you want to display it when you open the console add the following line to your ~/.bashrc file.

python /path/to/the/script.py

Happy Hacking! 🙂

Two months before i lost 10rs from my mobile balance without using it. When i contacted Reliance customer care they told me that “A joke pack has activated in your account by me last month and this is for the second time they are taking money,It is not possible to refund the money now, but they will deactivate it. It is possible to refund the money only within 24hours after activation of the pack.” I told them that i didn’t activate any such packs and told to deactivate it. On this month 25th i again noticed a decrease in balance by 10rs. So i contacted the customer care executive on 25th morning. He told that a joke pack has been subscribed that’s why i lost the money and it is possible to refund the money as no activation has yet taken place.So i told him to refund. As it didn’t got activate after an hour, i contacted the Customer care again. They told me to wait for 24hours. I waited for 24 hours and contacted them again on 26th evening and what they said was the same, to wait for 24hours. Told the same when i called them on 27th. When i called on 28th one CC executive told me that a complaint has been registered and that i have to wait for two days and i will be getting the complaint no as sms. Within two days i got two messages from them one containing the complaint number and the other informing that the offer pack has been deactivated. But the money was still not refunded. So i contacted them on 31st (yesterday), a CC executive told me that i will be surely refunded within 24hours and told me to wait. Today when i called them one guy telling me that my pack is not yet deactivated, i can deactivate it through an sms and it is not possible to refund the money. WTF??????

Yesterday i went to village office to get income certificate. To get subsidy in interest of educational loan from central govt we have to give income certificate to the bank. Village officer asked me about my native. I told him Palakkad. Then he asked about my father’s native. i told him Kottayam. Then he asked me if we have any property there, i nodded my head and told him we are living here for the past 30 years and we have nothing left there. He told me to get a report from the village office in Kottayam that we don’t have any property there. Then only he will give income certificate. i told him several times that we don’t have anything left there and we have property here. But he kept on saying the same. I should have lied that my father’s native is Palakkad. TIMES I HATE BEING A KOTTAYAM NATIVE

This time its the script to fetch the malayalam meanings of english words from malayalam wiktionary.

#!/usr/bin/python
#-*- coding: utf-8 -*-
# https://ragsagar.wordpress.com

from HTMLParser import HTMLParser
import urllib2,sys


class Parser(HTMLParser):
	
	def __init__(self):
		self.in_header = False
		self.in_definition = False
		HTMLParser.__init__(self)
	
	def handle_starttag(self, tag, attrs):
		if tag == 'li':
			self.in_header = True
		if tag == 'a' and self.in_header :
			self.in_definition = True
	
	def handle_endtag(self, tag):
	    	if tag == 'li':
			self.in_header = False
		if tag == 'a' :
			self.in_defintion = False
			
	def handle_data(self, data):
		if self.in_definition:
			print data 
			exit(0)
					


try :
	search_item = sys.argv[1]
except IndexError:
	print " syntax : %s <definiton> " % sys.argv[0]
	exit(1)
search_link = "http://ml.wiktionary.org/w/index.php?title=%s&printable=yes" % (urllib2.quote(search_item.encode('utf-8')))


request = urllib2.Request(search_link)
request.add_header('User-agent', 'Mozilla/5.0 (hb)')
try :
	response = urllib2.urlopen(request)
except urllib2.HTTPError :
	print "No definition found "
except urllib2.URLError :
	print "Unable to connect to internet "
else :
	parser = Parser()
	data = response.read()
	parser.feed(data)
			

Output in my terminal

malayalam meaning

Here is a script i wrote last night.It finds imdb rating of a movie.

#ragsagar[at]gmail.com
from mechanize import Browser
from BeautifulSoup import BeautifulSoup
import sys,re

if len(sys.argv) != 2:
	print "\nSyntax: python %s 'Movie title'" % (sys.argv[0])
	exit()
else :
	movie = '+'.join(sys.argv[1].split())

br = Browser()
br.open("http://www.imdb.com/find?s=tt&q="+movie)
link = br.find_link(url_regex = re.compile(r"/title/tt*"))
res = br.follow_link(link)
soup = BeautifulSoup(res.read())
try :
	title = soup.find('h1').contents[0].strip()
	rating = soup.find('span',attrs='rating-rating').contents[0]
	print "Movie : ",title
	print "Rating: ",rating,"/ 10.0"
except :
	print "Not Found!"	

Here is the screenshot of output.

Output of the script

%d bloggers like this: