Search This Blog

Loading...

Tuesday, March 25, 2008

Square Printing: Second Version

After yesterday's foray into Python programming, today I took a look at my code and decided to do some online search. My original code was too long, too verbose and too ugly that I couldn't hold my eyes on it for more than a second. After some searching, I managed to come up with the following version:


import operator
longstr = ''
for i in range(1, height+1):
for j in range(1, width+1):
if operator.or_(operator.or_(i==1,i==height),operator.or_(j == 1,j == width)):
longstr += '*'
else:
longstr += ' '
longstr += 'n'

print longstr

Does it look better?

4 comments:

peck said...

width = 25
height = 10

print '*' * width

line = '*' + (' ' * (width-2)) + '*'

for i in range(height):
print line

print '*' * width

Soon Hui said...

Thanks, peck, your version is a better one

Jason Scheirer said...

You can also abuse python's list comprehensions to get some terse code:

def box(width=5,height=5):
return '\n'.join(['*' * width] + ['*' + ' ' *(max([0, width-2])) + '*' for y in range(max([0, height-2]))] + ['*'*width])


>>> print box()
*****
* *
* *
* *
*****
>>> print box(4, 10)
****
* *
* *
* *
* *
* *
* *
* *
* *
****

etc etc etc

RAZAFY Lerina Jean-Yves said...

width=5
height=10

for i in range(height):
if i==0 or i==height-1:
print '*'*width
else:
print '*'+' '*(width-2)+'*'