COMP9021 Principles of Programming WEEK7 Optional

1. Default argument

如果function有多个argument,某些在定义的时候给定了default值,那么在调用的时候可以不写这样的argument。如下例:

def append_one_v1(L = []):
    L.append(1)
    return L

def append_one_v2(L = None):
    if L == None:
        L = []
    L.append(1)
    return L

for i in range(5):
    print(append_one_v1([0]))
    #每次都会创建一个新的[0],所以结果会是5个一样的[0,1]
print()
>>>
[0, 1]
[0, 1]
[0, 1]
[0, 1]
[0, 1]

for i in range(5):
    print(append_one_v1())
    #没有输入参数的情况下,不创建新的list,所以每次在原list中多加入一个1
print()
>>>
[1]
[1, 1]
[1, 1, 1]
[1, 1, 1, 1]
[1, 1, 1, 1, 1]

for i in range(5):
    print(append_one_v2([0]))
    #由于有输入参数,所以和v1是一致的
print()
>>>
[0, 1]
[0, 1]
[0, 1]
[0, 1]
[0, 1]

for i in range(5):
    print(append_one_v2())
    #虽然没有输入参数,但是v2给了None的判断方法,所以每次依然创建一个新的list
print()
>>>
[1]
[1]
[1]
[1]
[1]

2. Fibonacci review

def fibo(n, fibonacci = {0: 0, 1: 1}):
    if n not in fibonacci:
        fibonacci[n] = fibo(n - 1) + fibo(n - 2)
        #传递参数的时候可以不写第二个argument,因为是default
    return fibonacci[n]

3. Exerciese (Similar to Quiz5)

一个grid由自然数构成,上下左右定义为相邻,找到连续相邻的1的size,以一个list形式输出。

from random import randrange, seed

def print_grid():
    for row in grid:
        print(' '.join(str(int(e != 0)) for e in row))
            
def area_of_region_explored_from(i, j):
    area = 1
    grid[i][j] *= -1
    if j and grid[i][j - 1] > 0:
    #查询左侧有多少1
        area += area_of_region_explored_from(i, j - 1)
    if j < 9 and grid[i][j + 1] > 0:
    #查询右侧有多少1
        area += area_of_region_explored_from(i, j + 1)
    if i and grid[i - 1][j] > 0:
    #查询上方有多少1
        area += area_of_region_explored_from(i - 1, j)
    if i < 9 and grid[i + 1][j] > 0:
    #查询下方有多少1
        area += area_of_region_explored_from(i + 1, j)
    return area
            
seed(int(input('Input seed: ')))
density = int(input('Input density: '))
grid = [[randrange(density) for _ in range(10)] for _ in range(10)]
areas = []
for i in range(10):
    for j in range(10):
        if grid[i][j] > 0:
            areas.append(area_of_region_explored_from(i, j))

print_grid()
print(sorted(areas))

你可能感兴趣的:(COMP9021 Principles of Programming WEEK7 Optional)