Tanggal :October 22, 2020

# py26. Magic Function in Python

`# ex26.pyfrom __future__ import print_function, divisionimport numpy as npN = 11magic_num = sum(range(1,N**2+1))/Ndef mat(i,j):    i = i % N    j = j % N    return i,j    A = np.zeros((N,N))st = (N-1)/2,(N+1)/2for k2 in range(N):    st = st[0]+1,st[1]-1    for k in range(N):        A[mat(st[0]+k,st[1]+k)] = k+k2*N+1A = A.astype('int')AR = np.fliplr(A)print('magic(%d) = n%s' % (N,A))print('nmagic number = %d' % magic_num)print('sum primary diag = %d' % sum(A.diagonal()))print('sum secondary diag = %d' % sum(AR.diagonal()))for k2 in range(N):    print('sum row %d = %d' % (k2,sum(A[k2,:])))    print('sum col %d = %d' % (k2,sum(A[:,k2])))#magic(11) = #[[ 56 117  46 107  36  97  26  87  16  77   6]# [  7  57 118  47 108  37  98  27  88  17  67]# [ 68   8  58 119  48 109  38  99  28  78  18]# [ 19  69   9  59 120  49 110  39  89  29  79]# [ 80  20  70  10  60 121  50 100  40  90  30]# [ 31  81  21  71  11  61 111  51 101  41  91]# [ 92  32  82  22  72   1  62 112  52 102  42]# [ 43  93  33  83  12  73   2  63 113  53 103]# [104  44  94  23  84  13  74   3  64 114  54]# [ 55 105  34  95  24  85  14  75   4  65 115]# [116  45 106  35  96  25  86  15  76   5  66]]##magic number = 671#sum primary diag = 671#sum secondary diag = 671#sum row 0 = 671#sum col 0 = 671#sum row 1 = 671#sum col 1 = 671#sum row 2 = 671#sum col 2 = 671#sum row 3 = 671#sum col 3 = 671#sum row 4 = 671#sum col 4 = 671#sum row 5 = 671#sum col 5 = 671#sum row 6 = 671#sum col 6 = 671#sum row 7 = 671#sum col 7 = 671#sum row 8 = 671#sum col 8 = 671#sum row 9 = 671#sum col 9 = 671#sum row 10 = 671#sum col 10 = 671`