1. Default argument
如果function有多個(gè)argument烂完,某些在定義的時(shí)候給定了default值,那么在調(diào)用的時(shí)候可以不寫這樣的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]))
#每次都會(huì)創(chuàng)建一個(gè)新的[0]治唤,所以結(jié)果會(huì)是5個(gè)一樣的[0,1]
print()
>>>
[0, 1]
[0, 1]
[0, 1]
[0, 1]
[0, 1]
for i in range(5):
print(append_one_v1())
#沒有輸入?yún)?shù)的情況下,不創(chuàng)建新的list恋博,所以每次在原list中多加入一個(gè)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]))
#由于有輸入?yún)?shù),所以和v1是一致的
print()
>>>
[0, 1]
[0, 1]
[0, 1]
[0, 1]
[0, 1]
for i in range(5):
print(append_one_v2())
#雖然沒有輸入?yún)?shù)私恬,但是v2給了None的判斷方法债沮,所以每次依然創(chuàng)建一個(gè)新的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)
#傳遞參數(shù)的時(shí)候可以不寫第二個(gè)argument,因?yàn)槭莇efault
return fibonacci[n]
3. Exerciese (Similar to Quiz5)
一個(gè)grid由自然數(shù)構(gòu)成本鸣,上下左右定義為相鄰疫衩,找到連續(xù)相鄰的1的size,以一個(gè)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:
#查詢左側(cè)有多少1
area += area_of_region_explored_from(i, j - 1)
if j < 9 and grid[i][j + 1] > 0:
#查詢右側(cè)有多少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))