Created
November 7, 2013 10:05
-
-
Save elie222/7352140 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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