Python での関数

言語によって,関数と呼んだりプロシージャと呼んだりしますが,いずれにせよプログラムを構造化していくことにより,プログラミングが容易になります
また,再利用もしやすくなります
そこで,C言語での下のプログラムを基に Python へ書き換えます

#include <stdio.h>
#include <stdlib.h>
int makeSquare(int dim) {
  int a[99][99];
  int i = dim - 1;
  int j = (dim - 1) / 2;
  for (int num = 1; num <= dim * dim; num++) {
    a[i][j] = num;
    if (a[(i + 1) % dim][(j + 1) % dim] == 0) {
      i = (i + 1) % dim;
      j = (j + 1) % dim;
    } else {
      i = i - 1;
    }
  for (int i = 0; i <= dim - 1; i++) {
    for (int j = 0; j <= dim - 1; j++) {
      printf("%3d ", a[i][j]);
    }
    printf("\n");
  }
  return 0;
}
int main(int argc, char *argv[]) {
  int dim = atoi(argv[1]);
  float check = atof(argv[1]) - dim;
  if (dim > 0 && !check && dim % 2) {
    makeSquare(dim);
  } else {
    printf("Sorry!\nI can't make such a magic square.\nPlease let the argument an odd natural number.\n");
  }
  return 0;
}

何はともあれ,書き換えたプログラムを見ていただきましょう

def makeSquare(dim: int):
  a = [[0] * dim for i in range(dim)]
  i = int(dim - 1)
  j = int((dim - 1) / 2)

  for num in range(dim * dim):
    a[i][j] = num + 1
    if a[(i + 1) % dim][(j + 1) % dim] == 0:
      i = (i + 1) % dim
      j = (j + 1) % dim
    else:
      i = i - 1

  for i in range(dim):
    for j in range(dim):
      print(f'{a[i][j]: >4}', end = '')
    print('')

def magicSquare(dim: int):
  check = dim - int(dim)
  if dim > 0 and not check and dim % 2 :
    makeSquare(dim)
  else:
    print("Sorry!")
    print("I can't make such a magic square.")
    print("Please let the argument as an odd natural number.")

ん〜!やはり,Python でのコーディングは楽ですねぇ
C言語でのプログムができあがっていますから,当然,難しくはないのですが,それにしても気楽にコーディングすることができます
関数は次のとおりに作ります

関数を作る def

def 関数名(引数, 引数, ・・・):

関数の内容は,インデントを下げて記述します

プログラムの実行

対話形式にて,当該のファイルをインポートするだけで OK です

In [1]: from magicSquare import magicSquare

In [2]: magicSquare(5)
  11  18  25   2   9
  10  12  19  21   3
   4   6  13  20  22
  23   5   7  14  16
  17  24   1   8  15

In [3]: magicSquare(4)
Sorry!
I can't make such a magic square.
Please let the argument as an odd natural number.

または,このような記述もできます

In [1]: import magicSquare as ms

In [2]: ms.magicSquare(5)
  11  18  25   2   9
  10  12  19  21   3
   4   6  13  20  22
  23   5   7  14  16
  17  24   1   8  15

In [3]: ms.magicSquare(4)
Sorry!
I can't make such a magic square.
Please let the argument as an odd natural number.

最終更新日時: 2022年 03月 16日(水曜日) 06:28