Skip to content

Instantly share code, notes, and snippets.

@elie222
Created November 7, 2013 10:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elie222/7352140 to your computer and use it in GitHub Desktop.
Save elie222/7352140 to your computer and use it in GitHub Desktop.
from bottle import route, run, template
def createMagicSquare(n):
magicSquare = [[0]*n for i in range(n)]
# first position
loc = (0, n/2)
for i in range(1, (n*n)+1):
magicSquare[loc[0]][loc[1]] = i
loc = nextLoc(magicSquare, loc, n);
return magicSquare
def nextLoc(square, loc, n):
row = loc[0] - 1
col = loc[1] + 1
if row < 0:
row = n-1
if col >= n:
col = 0
# check if the square is empty. otherwise go down 1
if square[row][col] != 0:
col = loc[1]
row = loc[0]+1
if row >= n:
row = 0
return row, col
def printSquare(square):
for row in square:
print " ".join(["%5d" % cell for cell in row])
def main():
run(host='localhost', port=8080, debug=True, reload=True)
# magicSquare = createMagicSquare(7)
# printSquare(magicSquare)
# expected = sum(magicSquare[0])
# for row in magicSquare:
# assert sum(row) == expected
# for row in zip(*magicSquare):
# assert sum(row) == expected
# printSquare(zip(*magicSquare))
@route('/<n>')
def index(n='5'):
magicSquare = createMagicSquare(int(n))
return '<table border=1>%s</table>' % "\n".join(["<tr>%s</tr>" % "".join(["<td>%d</td>" % cell for cell in row]) for row in magicSquare])
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment