zoukankan      html  css  js  c++  java
  • Project2:解读percolation_provided

     

     Updated 1st:2011.8.7  

    Project2:解读percolation_provided

    这里咱们开始解读项目2中提供的percolation_provided.py,一共提供了4个函数,分别为:

    printgrid(grid): prints the grid represented by the nested list, one row per line (this module may be helpful in testing and debugging your code)

    printgrid(grid):输出用嵌套列表表示的网络,每排代表一行(这一模型可能对测试和调试你的代码有帮助)

    readgrid(filename): opens the file filename and returns the contents as a list of list (also helpful in testing and debugging your code)

    readgrid(filename):按文件名打开文件,并返回内容的列表清单(对测试和调试代码有帮助)

    grid(size,fill=0): returns a grid of dimensions size × size in which every grid location is initialized to fill. The default fill value is 0.

    grid(size,fill=0):按size × size返回网格大小,其中每个格子的位置都被初始化填充。默认填充值为0.

    visualize(flow_grid, input_grid): visualizes the flow through a grid using VPython

    visualize(flow_grid, input_grid):使用Vpython可视化流体经过网格

    1.第一个是grid(size,fill=0)函数,没多大技术含量,Key Point在于为生成一个nxn的网格,需要使用一个for..range语句,以及一个长度为n的列表作为行,然后另外一个空列表添加n行这样的列表。

    def grid(size, fill=0):
        
    """
        Make a grid with 'size' rows and 'size' columns, with each space filled by
        'fill'.

        >>> grid(3, 1)
        [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
        >>> grid(2, '*')
        [['*', '*'], ['*', '*']]
        
    """

    # 生成一个大小为sizeXsize的网格,默认填充为fill
        grid = []

        
    for i in range(size):
            row 
    = [fill]*size               # row is a list with size copies of fill
            grid.append(row)

        
    return grid


    2.第二个是printgrid(grid)函数,用来打印输出网格grid。

    def printgrid(grid):
        
    """
        Print out the grid represented in 'grid'.

        >>> printgrid([[1,0,1],[0,1,1],[0,0,1]])
         1  0  1
         0  1  1
         0  0  1
        >>>
        
    """

    #请注意print '%02s' % (space,),这句,其中(space,)中的逗号可省略,最后那个逗号不能省略,用于循环语句结束在同一行输出

    #当然你也可以尝试一下去掉看看会出现什么结果,下一行的print用于换行,最好的学习办法就是动手试试去掉了会出现什么
        for row in grid:
            
    for space in row:
                
    print '%02s' % (space,),
            
    print

     

    3.第三个乃是readgrid(filename)函数,咱们先来看看关于字符串的split()方法

    >>> help (str.split)

     Help on method_descriptor:
     
     split(...)
         S.split([sep [,maxsplit]]) 
    -> list of strings
     
      
       Return a list of the words in the string S, using sep as the
         delimiter string.  If maxsplit is given, at most maxsplit
         splits are done. If sep is not specified or is None, any
         whitespace string is a separator.
    说白了,这个方法默认就是往空格处切,然后就是打开文件filename,每次读一行(for line in file),然后弄个列表row。使用for语句把里面的元素按空格切开,依次读到x中,遍历添加到row里,如果文件读取到头了,那么row就为空列表了
    def readgrid(filename):
        
    """
        Reads the grid from the file.  The format is one row per line, each column
        separated by whitespace.

        >>> f = open('readgrid.test', 'w')
        >>> print >>f, '0 1 0\\n1 0 1\\n1 1 0\\n'
        >>> f.close()
        >>> readgrid('readgrid.test')
        [[0, 1, 0], [1, 0, 1], [1, 1, 0]]
        
    """

        file 
    = open(filename)
        grid 
    = []

        
    for line in file:
            row 
    = []
            
    for x in line.split():
                x 
    = int(x)                  # make x an integer, rather than string
                row.append(x)               

            
    if row != []:                   # filter out empty lines
                grid.append(row)

        
    return grid

    4.第四个是visualize(flow_grid, input_grid)函数,咱能先不谈么?对VPython的用法知之甚少啊。随便谈一下把,这个函数用来显示在flow_grid和input_grid中的流。使用灰方块表示阻塞位置,蓝方块表示流到的到位。

    def visualize(flow_grid, input_grid):
        
    """
        Visualize the flow in flow_grid on input_grid with VPython, using gray
        squares for blocked spaces (input_grid[i][j] = 1) and blue squares for
        spaces with flow (flow_grid[i][j] = '*').

        All objects in the scene will be removed prior to drawing.  The active
        scene will be used.

        >>> visualize([['*','*',1],['*',1,1],['*',1,1]], [[0,0,1],[0,1,1],[0,0,1]])
        
    """
        
    from visual import box, display

        blue = (0, 0, 1)
        gray = (.5, .5, .5)
        black = (0.30.30.3)

        size = len(input_grid)
        total_size = size * size
        disp = display.get_selected()       # gets the active display
        if disp is None:                    # no display, so create one
            display(title="Percolation", autocenter=True)
        
    else:                               # display exists, empty it
            disp.autocenter = True          # autocenter for convenience
            # We only need to delete these boxes if there is a mismatch in the
            # number of boxes versus the number of grid cells. We assume that no
            # other objects are on the scene.
            if total_size != len(disp.objects):
                
    for object in disp.objects:
                    object.visible = False  # make all objects in display invisible

        
    # redraw all of the grid, because of the size mismatch
        if total_size != len(disp.objects):
            
    for row in range(size):
                
    for col in range(size):
                    
    # for blocked spaces, draw a gray box
                    if input_grid[row][col]==1:
                        box(pos=(col, -row, 0), color=gray)
                    
    # for spaces with flow, draw a blue box
                    elif flow_grid[row][col]!=-1:
                        box(pos=(col, -row, 0), color=blue)
                    
    else:
                        box(pos=(col, -row, 0), color=black)
        
    # or just change the colors, based on the grids given
        else:
            
    for object in disp.objects:
                x, y, _ = object.pos
                x, y = int(x), int(y)
                
    if flow_grid[-y][x] != -1:
                    object.color = blue
                
    elif input_grid[-y][x] == 1:
                    object.color = gray
                
    else:
                    object.color = black

    def random_grid(size, p):
        
    """
        Generates a grid with 'size' rows and 'size' columns. Each grid space is
        randomly filled with a zero with probability p or a one with probability
        (1-p).
       
        >>> random_grid(3, 1)
        [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
        >>> random_grid(3, 0)
        [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
        
    """
        
    from random import uniform

        g = grid(size, 0)

        
    for row in range(size):
            
    for col in range(size):
                
    if uniform(0,1< p:        # true with probability p
                    g[row][col] = 0
                
    else:
                    g[row][col] = 1

        
    return g

    最后,这里关于doctest测试的使用,可以浏览  http://docs.python.org/library/doctest.html

    if __name__ == "__main__":

        
    import doctest
        doctest.testmod()


    None
  • 相关阅读:
    使用bottle进行web开发(2):http request
    使用bottle进行web开发(1):hello world
    python modules
    python的class的__str__和__repr__(转)
    functools模块方法学习(1):partial
    bottle框架学习(2):变量定义等
    VisualSVN_Server安装_配置图文教程
    管理的艺术--达尔文进化论:适者生存 末位淘汰
    LINUX怎么修改IP地址
    Cent OS 命令行和窗口界面默认登录切换方法
  • 原文地址:https://www.cnblogs.com/yuxc/p/2029764.html
Copyright © 2011-2022 走看看