Some source code

nnes pruebauno at latinmail.com
Sat Feb 21 23:14:51 EST 2004


For those that like to read source code, or just wondered how a C programmer
would use Python I post some code written by a friend which I pestered to at
least try Python out. He did not seem too impressed after the exercise, but said
it was not that painfull :-).

It might be of interest to those wondering how python is being used and misused
:-). I guess teachers using Python to teach can confirm or deny the benefits of
certain language decisions daily by looking at the source code of their
students.

Anyway here we go:

#
# Reading File and loading it

#Hashing a string with a specified separator
# and storing results in an Array
#
def HashString(str,sep):
	lim = len(str)
	array=[]
	indexes=[]
	cptr =0
	for i in range(lim):
		if str[i]== sep and i < lim: 
			indexes.append(i)
			cptr+=1
		
	lim = len(indexes)
	cptr =j=0
	for i in range(lim-1):
		if(str[j] == sep and j ==0) :
			j+=1
			cptr+=1
		array.append(str[j:indexes[cptr]])
		j=indexes[cptr]+1 
		cptr+=1

	return array;
#
#	End of HashString Function
#

File= open('input.txt','r')
content=[]
content = File.readlines()
sum =0
Result = []
OFile = open('output.txt','w')
for i in range(len(content)):
	result = HashString(content[i],'\"')
	cptr=sum = 0
	for j in range(len(result)):
		sum += int(result[cptr])
		if(j>0):
			OFile.write(",")
		OFile.write("\""+result[cptr]+"\"")
		cptr+=2
		if cptr >= len(result) : break;
	OFile.write(",\""+sum.__str__()+"\"\n")
	result.append(sum)
	print result
#
# Creating Ouput file
#
OFile.close();
File.close();
print "\n....\tdone view output in \'output.txt\'.......\n"


#######################################

Roughly does this:

file('output.txt','w').writelines(['%s,"%s"\n' % (line[:-1],
    sum(map(int,line[1:-2].split('","')))) for line in
    file('input.txt')])



More information about the Python-list mailing list