Beginning Python Visualization: Crafting Visual Transformation Scripts

Page 263

C H A P T E R 7 N M A T H G A M E S

Listing 7-5. Creating a Magic Square bnki jqilu eilknp & `ab i]ce_om$j9/%6 Napqnjo ] i]ce_ omq]na kb oeva j7 j iqop ^a k`` eb j ! . 9 -6 n]eoa R]hqaAnnkn( I]ce_$j% namqenao j pk ^a k`` i( nks( _kh 9 vanko$Wj( jY%( ,( j+. bkn jqi ej tn]jca$-( j&&.'-%6 iWnks( _khY 9 jqi behh pda _ahh _kh 9 $_kh'-% ! j nks 9 $nks)-% ! j eb iWnks( _khY6 _kh 9 $_kh)-% ! j nks 9 $nks'.% ! j napqnj i `ab paopi]ce_om$i%6 Napqnjo Pnqa eb i eo ] i]ce_ omq]na* ioqi 9 oqi$iW,( 6Y% napqnj ]hh$i*oqi$,% 99 ioqi% ]j` ]hh$i*oqi$-% 99 ioqi% The main bkn loop is quite straightforward and follows the algorithm strictly. However, calculation of the column and row values using the modulo (!) operator is tricky and requires some explanation. Consider the way the algorithm is specified: increment the column value and check whether the new value is within the size of the matrix. If it is not, wrap it around to the beginning. A similar approach is taken with the row: decrement and wrap if required. Instead of implementing these two steps, an increment/decrement followed by an eb statement, we could use the modulo operation, which captures the idea quite elegantly: _kh 9 $_kh'-% ! j. I’ve chosen to initialize the variables i, nks, and _kh with a multiple assignment. Multiple assignments can also be used inside the bkn loop: _kh( nks 9 $_kh'-% ! j( $nks)-% ! j; however, in my mind it’s less clear, and there’s no impact performance-wise. My personal preference is to use multiple assignments in initializations and not calculations. I’ve defined another function here, paopi]ce_om$%, which checks whether a square is indeed a magic square. The function also works on even values (which is a plus) and makes use of the oqi$% member function of the array object.

NTip Python supports testing via several built-in packages, including `k_paop and qjeppaop. However, for the purpose of this example, I’ve chosen to write a dedicated test function, which will further show the properties of NumPy arrays.

245


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.