Code Ghar

Random Sequence Generator in Python

Posted in code by hs on September 9, 2009

I needed to generate random numbers but in sequence within a certain range. For example, I could generate 10,000 numbers in the range of 1000 to 9999. Rather than generate this range in sequence, I needed to generate this sequence randomly. For this exercise, random is your friend. How did I do it? The code is as below:

from random import randrange, shuffle

randomlist = []
uniqueflag = False
total_to_generate = 40000
start_range = 10000
end_range = 99999

for i in xrange (1,total_to_generate+1):
    while not uniqueflag:
        randomnumber = randrange(start_range,end_range)
        if randomnumber not in randomlist and randomnumber not in (11111, 22222, 33333, 44444, 55555, 66666, 77777, 88888, 99999):
            uniqueflag = True
    randomlist.append(randomnumber)
    uniqueflag = False
shuffle(randomlist)
for x in randomlist:
    print x

You can change total_to_generate, start_range, and end_range according to your needs. I chose to exclude 11111, 22222, and so on, because they are the easiest to guess and if you need random numbers, better to exclude them. I also chose to shuffle to add a bit more randomness.

I named the file rando.py and used it as below. Since the code prints to standard output, I chose to redirect the output to a file to save the numbers.

python rando.py > numbers.txt

Hat tip to: How do I generate random numbers in Python?; shuffling elements of a list.

Tagged with:

Python: Tabs or Spaces

Posted in discussion by hs on November 18, 2008

I never understood the controversy surrounding tabs and spaces in indenting Python code. Lots (and I mean lots) of people do not like using tabs (or so I thought) in Python. And a question I had to ask was: what’s wrong with using tabs? Why not use tabs? Why use spaces?

I have to admit I love using the tab key. It makes indenting so easy. Instead of typing four spaces, I type one tab. I am also a lone developer: my code never sees the light of day on any other developer’s computer. So whatever I do works for me. But that’s not how it should be. I should consider good practices and implement them in my daily habits. So I embarked on a mission to find out once and for all why to use spaces instead of tabs.

Turns out I was looking at it the wrong way. I started off with Python track: coding style guide. It said, “Never, ever, ever use the tab character (ascii 0×9)!” I also saw Python: Myths about Indentation, which said, “it is generally a good idea not to mix tabs and spaces for indentation. If you use tabs only or spaces only, you’re fine.” To be very honest, I did not still get why tabs should not be used.

I finally stumbled (ok, googled) upon OT: Tab characters considered harmful (Was: Emacs has eaten my python tabs!!!). This is when I finally understood the controversy: “Lest anyone get me wrong, I am in no way opposed to using the Tab *key* on your keyboard to indent lines.” OK, so that’s it. One may use the tab key but not the tab character. I was confused between the key and the character. But to use the tab key, you should configure your editor to convert tab key into space characters, not tab character. Then you can continue to use tab keys and still be compliant with the practice of using spaces for indentation.

Tagged with:

Project Euler Solutions

Posted in code by hs on December 20, 2007

Head to Project Euler to solve mathematical problems using programming. I am cheating. I should not post these solutions but I want to get feedback on the quality of solutions implemented. The results are correct but are they generated from “quality” code? Only by sharing the code can I and others know.

Why am I using Python? Because this way I can learn how to program in it. Plus I get to learn more math.

Problem 1


import sys
def multipleof (multiple = 1, integer = 1):
	try:
		return (int(int(multiple) % int(integer)))
	except:
		print 'error for multiple %s and integer %s' % (multiple, integer)
		print 'error was', sys.exc_info()[0]
		raise
sum = 0
for multiple in range (1, 1000):
	try:
		if multipleof (multiple, 3) == 0 or multipleof (multiple, 5) == 0:
			sum += multiple
	except:
		pass
print 'The sum is ', sum
Tagged with:

Learn Python

Posted in discussion by hs on December 19, 2007

I haven’t had too much experience in Python. I start learning it then something else comes up. After some time I pick it up again but something else happens. So I know of Python and know some Python but don’t actually know Python. If you are in the same boat, these resources will help you very much in getting to the next level.

Byte of Python. This is a free online book which teaches you Python.

Dive Into Python. This book is a very good place to learn Python.

Building Skills in Python. This is another book which will help you with Python.

The Python Challenge. According to the website: “Python Challenge is a game in which each level can be solved by a bit of (Python) programming.”

Project Euler. This website provides mathematical problems that you have to solve by programming. And if you solve them in Python, you kill two birds with one stone: learn math and learn Python.

The way I would like to really learn Python is to read the books, try their examples, and then work on the challenges that make you not only think of algorithms but also how to implement them. Such comprehensive learning is what we should all want.

Tagged with:

Simple Heartbeat System

Posted in code by hs on December 11, 2007

The purpose of this system is to make sure a group of computers can keep track of each other’s well being. If one or more systems is unable to respond to a network request, we immediately assume something went wrong.

This combination of client-server scripts has been written in Python. All it does is this: a client sends a message periodically to the server. The server echoes back whatever the client sent. If the client has any problems connecting with the server or does not receive an echo, it sends an email to whoever you want to and then quits.

I tried to make the client script keep running after sending an email but then decided against it. The reason was that I would prefer to manually check the problem and fix it rather than have the client try to fix it itself.

The code used here was inspired by: (a) Sending email in python; (b) Simple echo server; and (c) Simple echo client.

You will need two files on the client side: echoclient.py and message.txt where message.txt will contain the message to be emailed. The server will only need echoserver.py and no other file.

echoserver.py

#!/usr/bin/python
import socket
host = ''
port = 550000
backlog = 5
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
while (1):
	client, address = s.accept()
	data = client.recv(size)
	if data:
		client.send(data)
	client.close()

echoclient.py

#!/usr/bin/python
import socket
import time
import smtplib
smtpserver = 'smtp.domain.com'
AUTHREQUIRED = 1 # if you need to use SMTP AUTH set to 1
smtpuser = 'user@domain.com'  # for SMTP AUTH, set SMTP username here
smtppass = 'password'  # for SMTP AUTH, set SMTP password here
RECIPIENTS = ['user1@domain.com','user2@domain.com','user3@domain.com']
SENDER = 'user@domain.com'
MESSAGE_TO_SEND = 'message.txt'
host = '192.168.168.100'
port = 550000
size = 1024
while (1):
	try:
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.connect((host,port))
		s.send('Hello, world')
		data = s.recv(size)
		s.close()
		print 'Received from ', host, ': ', data
		time.sleep (10)
	except:
		print 'There has been some problem with the connection... Sending email(s) to ', RECIPIENTS
		mssg = open(MESSAGE_TO_SEND, 'r').read()
		session = smtplib.SMTP(smtpserver)
		if AUTHREQUIRED:
			session.login(smtpuser, smtppass)
		smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg)
		if smtpresult:
			errstr = ""
			for recip in smtpresult.keys():
				errstr = """Could not deliver mail to: %s
				Server said: %s
				%s
				%s""" % (recip, smtpresult[recip][0], smtpresult[recip][1], errstr)
			raise smtplib.SMTPException, errstr

message.txt

To: user@domain.com
From: user@domain.com
Subject: Heartbeat Problem

The server on this IP is not responding to heartbeat. Please investigate.

Please remember to put an empty line between the “Subject” line and the actual message in message.txt.

I assumed the authors wanted their code to be used freely because they had posted this code for the sole purpose of teaching people like myself how to do this stuff. If this is not the case, I would be glad to remove your copyrighted content.

Tagged with:

Connect to Database Using Python

Posted in configuration by hs on December 8, 2007

Although you can connect to databases using Python on many platforms, the specific examples here are on Ubuntu.

MySQL

If you would like to connect to MySQL using Python, the process is quite simple. You will need MySQLdb. In Ubuntu, it is quite easy to install

sudo apt-get install python-mysqldb

Once you have installed it, you are ready to go. How do you actually connect to it? I would rather let people smarter than me explain it. One such resource is Using the MySQLdb Interface.

Microsoft SQL Server

A fantastic guide for beginners has been provided at Accessing MSSQL using Python on Ubuntu. Head over there to read how to do it. Some useful links: pymssql, freetds, and ubuntu freetds.

However, I can also try to customize install instructions here.

sudo apt-get install python2.5-dev freetds-dev build-essential

You have to download the pymssql module, but choose the platform independent files, not Windows specific. After downloading (I am assuming the .zip file), you may install it using the following steps:

unzip pymssql-0.8.0.zip

cd pymssql-0.8.0

sudo python setup.py install

To see how to use it in your scripts, try Example script – pymssql module, Example script – _mssql module, or Accessing MSSQL using Python on Ubuntu.

Tagged with: , , ,