Skip to main content
 首页 » 编程设计

python之为幻方写一个类型契约(Contract)

2025年05月04日13haluo1

我被要求为这个幻方编写代码。

A two dimensional integer matrix s is a magic square if

  1. The dimensions of s is nxn
  2. Every integer in [1,2,...,n*n] appears in s, exactly once.
  3. The sum of all rows in s is the same as the sum of all columns in s, is the same as the sum of the diagonal elements in s.

Example: s=[[8, 3, 4], [1, 5, 9], [6, 7, 2]] represents the following integer matrix:

8 3 4 
1 5 9 
6 7 2 

Note that s above is a two dimensional integer array

  1. s is a 3x3 square
  2. All numbers in [1,2,...,9] appear in s exactly once.
  3. The sum of all rows is the same as the sum of all columns is the same as the sums along both diagonals.

    • Row sums: 8+3+4 == 1+5+9 == 6+7+2 == 15
    • Col sums: 8+1+6 == 3+5+7 == 4+9+2 == 15
    • Diag sums: 8+5+2 == 6+5+4 == 15

Example: The following are also magic: [[8, 1, 6], [3, 5, 7], [4, 9, 2]], [[6, 7, 2], [1, 5, 9], [8, 3, 4]]

我了解如何编程和编写此代码,但我的问题是如何为此编写类型契约(Contract)。我知道如何编写一个程序来执行它,但是当涉及到任何程序的类型契约(Contract)时,你怎么知道会有多少参数,你怎么知道如何编写你想要它做什么的例子对于这样的程序。在编写类型契约和为程序制作示例时是否有一个通用的方法可以遵循?

请您参考如下方法:

在检查 array 是否如您的文档字符串所说的那样方面,我实际上不会打扰。使用 duck typing ;假设这是正确的事情,并让调用者处理如果他们没有传递您要求的内容而导致的任何错误。

如果输入无效,您的函数将无法继续,因此在该级别处理错误并尝试显式使用例如isinstance 只会进一步缩小用户可以传入的内容,而不是必要的(例如,如果用户传入元组的元组而不是列表的列表,为什么你的函数不能继续工作?他们都是序列...)。


如果您的问题真的是关于包含示例,正如您的评论所暗示的那样,那么我将从这里开始:

def is_magic(array): 
    """Whether the array is 'magic'. 
 
    Arguments: 
      array (sequence of sequences of integers): The array to test. 
 
    Returns: 
      bool: Whether the array is 'magic'. 
 
    Notes: 
      A 'magic' array is a 3x3 array of integers where each row, column 
      and diagonal adds up to the same number 
 
    Examples: 
 
        >>> is_magic([[8, 3, 4], [1, 5, 9], [6, 7, 2]]) 
        True 
 
    """ 
    raise NotImplementedError 
 
if __name__ == '__main__': 
    import doctest 
    doctest.testmod() 

docstring记录该功能,并且可以被例如使用IDE 和 help 函数告诉用户该函数的作用。注意 doctest 的使用示例,它们都向用户展示了如何调用该函数以及期望返回什么,并作为您代码的测试。

当然,当你第一次运行它的时候,它会失败......

********************************************************************** 
File "C:\Python27\so.py", line 16, in __main__.is_magic 
Failed example: 
    is_magic([[8, 3, 4], [1, 5, 9], [6, 7, 2]]) 
Exception raised: 
    Traceback (most recent call last): 
      File "C:\Python27\lib\doctest.py", line 1315, in __run 
        compileflags, 1) in test.globs 
      File "<doctest __main__.is_magic[0]>", line 1, in <module> 
        is_magic([[8, 3, 4], [1, 5, 9], [6, 7, 2]]) 
      File "C:\Python27\so.py", line 20, in is_magic 
        raise NotImplementedError 
    NotImplementedError 
********************************************************************** 
1 items had failures: 
   1 of   1 in __main__.is_magic 
***Test Failed*** 1 failures.