Last active
August 29, 2015 14:02
-
-
Save CortYuming/9446510c4afc8184d2d2 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
#!/usr/bin/env python | |
# *-# -*- coding: utf-8 -*- | |
""" | |
魔法陣 Wikipedia | |
http://ja.wikipedia.org/wiki/%E9%AD%94%E6%96%B9%E9%99%A3#.E9.AD.94.E6.96.B9.E9.99.A3.E3.81.AE.E4.BD.9C.E3.82.8A.E6.96.B9 | |
ヒンズーの連続方式[編集] | |
1. 上段の中央を1にする | |
2. 右上に次の数字を置いていく(最上段の上は最下段になる。下の図を参照。) | |
3. 右上が埋まっていたら一つ下に次の数字を置く | |
4. 再び右上へと数字を埋めていく | |
5. 後は3,4の繰り返しで完成 | |
""" | |
def is_even(num): | |
return num % 2 == 0 | |
def magic_square(square_num): | |
if is_even(square_num): | |
return | |
square = [[None for _ in range(square_num)] for _ in range(square_num)] | |
row = 0 | |
column = square_num / 2 | |
for number in range(1, square_num ** 2 + 1): | |
if 1 < number: | |
row -= 1 | |
if row < 0: | |
row += len(square) | |
column += 1 | |
if len(square) <= column: | |
column = 0 | |
if square[row][column] is not None: | |
row += 1 | |
if len(square) <= row: | |
row = 0 | |
square[row][column] = number | |
return square | |
if __name__ == '__main__': | |
for row in magic_square(3): | |
print(row) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment