Sunday, March 25, 2007

Python Power

A friend once had a problem with this code ... didn't know what was going on. Took ages to debug a simple problem and gave up ...

f = open('test.txt','r')
for line in f.read().split(','):
if i == 0:
z = line
print 'X1 = '+z
elif i == 1:
a = line
print 'a! = '+a
elif i == 2:
b = line
print 'b! = '+b
elif i == 3:
c = line
print 'c! = '+c
i = 0
i = i + 1
#training(x1, a, b, c)

Its 18 lines long, a pain in the @$$ to debug, and frankly ... too much bull$#!t ...
1st step, bring your logic up a level and stop thinking like stupid one dimensional programmers, start thinking like a errrr.... a 'person'. 2nd step, keep it simple...

If you do these 2 steps right, you might get something like this ...

f = open('test.txt','r')
linelist = f.readlines()
for line in linelist[1:]:
var=line.split(',')
print linelist[0].strip(),var[0],var[1],var[2]


Its 5 lines long ... took 2 minutes to think of and write and it does exactly the same stuff that the previous one was supposed to do.

May his experience be a lesson to all ...

Labels:

1 Comments:

  • gile kejam.. transition from java to python memang susah le, aku pun tak sure bila aku lepas dari genggaman :D

    By Blogger :: unexistance ::, at 8:29 PM  

Post a Comment

<< Home