0

我应该看看这个模型解决方案,以便为我的下一个班级分配工作。该程序返回 32 到 126 之间的 ASCII 值。在“for 语句”之前,我一直在理解它。有人可以帮我看看吗?我知道这与创建四列有关,但我认为在继续之前了解它的每一点都是有益的。

非常感谢。

START = 32

END = 126


def GiveAscii(start=START, end=END, width=4):

    """Returns an ascii chart as a string. Readable."""

    entries = end - start +1
    entries_per_column = entries/width
    if entries % width:
        entries_per_column += 1
    ret = []
    for row in range(entries_per_column):
        for column in range(width):
            entry = entries_per_column * column + row + start
            if entry > end:
                break
            ret += ["%3d = %-6s" % (entry, chr(entry))]
        ret += ['\n']
    return ''.join(ret)

def main():
    print GiveAscii()

if __name__ == '__main__':
    main()
4

2 回答 2

0

第一个枚举从零到值的范围entries_per_column作为一个名为的变量row

对于每一行,都有一个从零到值的枚举,width作为一个名为的变量column

所以这是创建一个二维矩阵 - 应该很容易消化。

对于columna中的每个row,该空间中的值都分配给变量entry。如果entry不超过矩阵的最大值,则将其作为列表放入返回列表ret中。在这之后ret给出一个换行符,以便可以在视觉上创建一个新行(当ret打印出来时)。所以这个程序创建了一个列表 ,ret其中包含一个二维矩阵值 - 多个列表 s,每个列表都包含一些称为s 的row单值列表,其中包含它们。columnentries

我希望这很清楚!

于 2013-06-17T21:48:14.483 回答
0

我决定评论你的代码,看看它是否可以帮助你

START = 32

END = 126

# A function to return a string which represents an asci grid
def GiveAscii(start=START, end=END, width=4):

    """Returns an ascii chart as a string. Readable."""
    # The number of entries is the end minus the start plus one
    entries = end - start +1
    # Doing an integer devide provides us with the floor of the entries per column
    entries_per_column = entries/width
    # If our division was not even
    if entries % width:
        # We need to add an extra entry per column
        entries_per_column += 1
    # Initialize our array
    ret = []
    # For every row
    for row in range(entries_per_column):
        # Go through every column
        for column in range(width):
            # Do this math to create this entry, multiply first!
            entry = entries_per_column * column + row + start
            # If the entry is larger than the value end
            if entry > end:
                # Leave this column
                break
            # Not really sure what this formatting is but it is a formatting statment
            # Char casts your number as a character
            ret += ["%3d = %-6s" % (entry, chr(entry))]
         # When we are done with our column print and endline charachter
         ret += ['\n']
    # Return your array
    return ''.join(ret)

def main():
    print GiveAscii()

if __name__ == '__main__':
    main()
于 2013-06-17T21:49:48.037 回答