9.
有些內建函式是定義在各別套件中,要使用這些內建函式時,必須先
使用import指令引用套件
import 套件名稱
import math #匯入math套件,並可使用math套件內的任何函式
程式中必須以「套件名稱.函式名稱」呼叫套件內的函式
print(math.sqrt(100))
匯入套件時可指定別名,程式中要呼叫套件內的函式時,要在函式前
要加上別名名稱
import math as M
print(M.sqrt(100))
import指令 1/2
9
10.
若覺得以「套件名稱.函式名稱」呼叫套件內的函式有些麻煩,可改用
from .. import指令
from 套件名稱 import *
from math import * #匯入math套件,並可使用math套件所有函式
print(sqrt(100))
若只要匯入套件中的特定函式,如 sqrt(),其匯入時敘述為
from math import sqrt #只匯入math.sqrt函式,不可使用math套件的其它函式
print(sqrt(100))
匯入套件指定函式時,也可以設定函式別名
from math import sqrt as squareRoot
print(squareRoot(100)) #匯入math套件中的sqrt函式,並指定函式別名
#squareRoot(100)與sqrt(100)是⼀樣的效果
import指令 2/2
10
11.
數值的內建函式還有定義在 math 套件中的數值函式,例如 sin()、
exp()、log() 等
要使用 math 套件內的函式,必須在使用前匯入 math 套件
import math
math套件函式 1/2
函式 說明 範例
pi 圖週率常數 (3.141592653589793) num = math.pi #3.14...
e 數學常數 (2.718281828459045) num = math.e #2.71...
ceil(n) 取得大於n的最小整數 num = math.ceil(12.3) #13
floor(n) 取得小於n的最大整數 num = math.floor(12.3) #12
fabs(n) 取得浮點數n的絕對值 num = math.fabs(-12.3) #12.3
sqrt(n) 取得n的平方根 num = math.sqrt(169) #13.0
11
12.
math套件函式 2/2
函式 說明 範例
exp(n) 取得n自然指數值(𝑒 ) num = math.exp(1) #2.71...
log(n) 取得n自然對數值(𝑙𝑜𝑔 𝑛) num = math.log(math.e) #1.0
sin(n) 取得弳度為n的正弦函式值 num = math.sin(math.pi/6) #0.5
cos(n) 取得弳度為n的餘弦函式值 num = math.cos(math.pi/3) #0.5
tan(n) 取得弳度為n的正切函式值 num = math.tan(math.pi/4) #1
asin(n) 取得反正弦函式的弳度值 num = math.asin(0.5) #π/6
acos(n) 取得反餘弦函式的弳度值 num = math.acos(0.5) #π/3
atan(n) 取得反正切函式的弳度值 num = math.atan(1) #π/4
12
32.
def gcd(x, y):
while ( x > 0 and y > 0 ):
if(x > y): x = x % y
else: y = y % x
return y if (x == 0) else x
while True:
a = eval(input('輸入第⼀個正整數a:'))
b = eval(input('輸入第二個正整數b:'))
if a > 0 and b > 0:
break
else:
print('無效輸入, 請重新輸入...')
gcd = gcd(a, b)
print('%d, %d 兩整數的GCD為 %d' %(a, b, gcd))
print('%d, %d 兩整數的LCM為 %d' %(a, b, (a * b)/gcd))
測試結果:
輸入第⼀個正整數a:234
輸入第二個正整數b:36
234, 36 兩整數的GCD為 18
234, 36 兩整數的LCM為 468
實作練習 2/2
32
37.
def inc(x):
print('id of x = %d' %id(x), end = ', ')
print('x = %d' %(x))
x += 1
print('id of x = %d' %id(x), end = ', ')
print('x = %d' %(x))
a = 10
print('id of a = %d' %id(a), end = ', ')
print('a = %d' %(a))
inc(a)
print('id of a = %d' %id(a), end = ', ')
print('a = %d' %(a))
測試結果:
id of a = 140729614147616, a = 10
id of x = 140729614147616, x = 10
id of x = 140729614147648, x = 11
id of a = 140729614147616, a = 10
引數的傳遞方式 2/9
37
39.
def additem(x):
print('id of x = %d' %id(x), end = ' ,')
print('x = ', x)
x.append(5)
print('id of x = %d' %id(x), end = ' ,')
print('x = ', x)
a = [1, 2, 3, 4]
print('id of a = %d' %id(a), end = ' ,')
print('a = ', a)
additem(a)
print('id of a = %d' %id(a), end = ' ,')
print('a = ', a)
測試結果:
id of a = 2398559902016 ,a = [1, 2, 3, 4]
id of x = 2398559902016 ,x = [1, 2, 3, 4]
id of x = 2398559902016 ,x = [1, 2, 3, 4, 5]
id of a = 2398559902016 ,a = [1, 2, 3, 4, 5]
引數的傳遞方式 4/9
39
48.
Lambda函式是⼀種特別的函式
它是匿名函式,不需要定義名稱,且函式程式碼只能有⼀行指令敘述。語
法如下:
lambda 參數1, 參數2, ...:程式碼
下列max()函式會回傳二數中較大者
def max(m, n):
if m > n:
return m
else:
return n
可改寫如下
def max(m, n):
return m if m > n else n
lambda函式 1/5
48
49.
若將max()函式轉換成lambda函式,程式如下
max = lambda m, n : m if m > n else n
print(max(10, 3))
Lambda函式支援IIFE (immediately invoked function expression) 語
法,意思是利用 function expression 的方式來建立函式,並且立即執
行它,語法如下:
(lambda 函式參數:指令敘述)(實引數)
print((lambda m, n:m if m > n else n)(10, 3))
lambda函式 2/5
49
68.
有n個不同的物品,要挑出 k 個的方法數有幾個?這是數學上「組合」
的題目,我們用 C(n, k) 來表示。若有針對某個特定物品,會分成兩種
互斥情況:
1. 選到這個特定物品,就再從剩下的n-1個物品中挑出k-1個物品,則會有
C(n-1, k-1)個方法數
2. 沒有選到這個特定物品,就再從剩下的n-1個物品中挑出k個物品,則會有
C(n-1, k)個方法數
所以,當 n = k 或 k = 0 時,則 C(n, k) = 1;
當 n > k 時,則
C(n, k) = C(n-1, k-1) + C(n-1, k)
遞迴應用實例 8/12
68
69.
def C(n, k):
if n == k or k == 0:
return 1
else :
return C(n - 1, k - 1) + C(n - 1, k)
while True:
n = eval(input('n = '))
k = eval(input('k = '))
if n >= 0 and k >= 0 and n > k:
break
else:
print('輸入資料不符, 請重新輸入...')
ans = C(n, k)
print('組合 C(%d, %d) = %d' %(n, k, ans))
測試結果:
n = 5
k = 2
組合 C(5, 2) = 10
遞迴應用實例 9/12
69
70.
河內塔問題
有三根杆子A,B,C。A杆上有 N 個 (N>1) 穿孔圓盤,盤的尺寸由下到上依
次變小。要求按下列規則將所有圓盤移至 C 杆:
每次只能移動⼀個圓盤
大盤不能疊在小盤上面
提示:可將圓盤臨時置於 B 杆,也可將從 A 杆移出的圓盤重新移回 A 杆,
但都必須遵循上述兩條規則
遞迴應用實例 10/12
70
A B C
A B C
71.
將⼀個 N 層河內塔由 A 桿移到 C 桿。依照上面的解法
先將前 N-1 層的圓盤先移到 B 桿
再將第 N 層的圓盤移到 C 桿
將 B 桿上的圓盤全部移到 C 桿
遞迴應用實例 11/12
71
72.
def Hanoi(n, a, b, c):
if n == 1:
print('move %d %s --> %s' %(n, a, c))
return
Hanoi(n - 1, a, c, b)
print('move %d %s --> %s' %(n, a, c))
Hanoi(n - 1, b, a, c)
n = int(input('Number of rings on A: '))
Hanoi(n, 'A', 'B', 'C')
測試結果:
Number of rings on A: 3
move 1 A --> C
move 2 A --> B
move 1 C --> B
move 3 A --> C
move 1 B --> A
move 2 B --> C
move 1 A --> C
遞迴應用實例 12/12
72
78.
玩家回合作業
def player_turn():
global total
run = True
while (run):
try:
take = int(input('要取走幾個⽯子頭(1~%d):' %max_take))
if (take >= 1 and take <= max_take):
run = False
total = total - take
print('玩家取走%d個⽯子,剩下%d個' %(take, total))
else:
print('只能取走1~%d個⽯子' %max_take)
except:
print('必須輸入數值')
應用實例:輪流取物遊戲 5/7
78
79.
電腦回合作業
def computer_turn():
global total
take = (total - 1) % (max_take + 1)
if (take == 0):
take = random.randint(1, max_take)
total = total - take;
print('電腦取走%d個⽯子,剩下%d個' %(take, total))
應用實例:輪流取物遊戲 6/7
79
84.
#顯示所有回合猜測值及結果
def show_detail(guesslist, resultlist):
for i in range(len(guesslist)) :
print ('(%d) %s/%s' % (i + 1, guesslist[i], resultlist[i]))
#比對guess與answer數值字串內容,回傳?A?B之a, b值
def check(guess, answer):
a = b = 0
for i in range(4):
if guess[i] in answer:
if i == answer.find(guess[i]) :
a += 1
else:
b += 1
return a, b
應用實例:猜數字遊戲 4/11
84
85.
#找下⼀組數值不重複的4位數數值字串
def next_guess():
global guess
if (guess < 123):
print('提示有誤,請重新檢查')
sys.exit()
while (True):
temp = guess
tempguess = ['0', '0', '0', '0']
for i in range(3, -1, -1):
tempguess[i] = chr(temp % 10 + 48)
temp //= 10
computer_guess = ''.join(tempguess)
for ch in computer_guess: #檢查數字字串是否有重複的數字
if (computer_guess.count(ch) > 1):
guess -= 1 #換下⼀個數字
break;
else:
return computer_guess #回傳猜測值
應用實例:猜數字遊戲 5/11
85
86.
#驗證猜測值的合理性,假設猜測值為正確答案,那麼與先前所有猜測值應得到同樣的比對結果
def is_reasonable(numstr):
for c in range(len(computerNums)):
a, b = check(numstr, computerNums[c])
if ((chr(a + 48) != computerHints[c][0]) or
(chr(b + 48) != computerHints[c][2])):
return False #與先前比對結果不吻合
return True
應用實例:猜數字遊戲 6/11
86
87.
#玩家回合處理作業
def player_turn():
wellform = False
while (wellform == False):
user_guess = input('輸入四個不重複數字:')
if (user_guess.isdigit() == False) :
print ('***錯誤:只能輸入數字,請重新輸入')
continue
if (len(user_guess) != 4) :
print ('***錯誤:必須輸入四個數字,請重新輸入')
continue
for ch in user_guess: #檢查是否有重複的數字
if (user_guess.count(ch) > 1):
print ('***錯誤:數字不可重複,請重新輸入')
break
else:
wellform = True
應用實例:猜數字遊戲 7/11
87
88.
a, b = check(user_guess, answer) #檢查猜測結果
result = '%dA%dB' %(a, b)
print(result)
playerNums.append(user_guess) #記錄猜測值
playerHints.append(result) #記錄答案提示
return (a == 4)
應用實例:猜數字遊戲 8/11
88
90.
a = int(input('有幾個數字及位置都正確?'))
b = int(input('有幾個數字正確,但位置不正確?'))
result = '%dA%dB' %(a, b)
print(result)
if (a == 4):
return True
else:
computerHints.append(result) #記錄猜測提示
computerNums.append(computer_guess) #記錄猜測結果
guess -= 1
return False
應用實例:猜數字遊戲 10/11
90
91.
#主程式
while (True):
print ('-' * 20)
print('player's turn')
show_detail(playerNums, playerHints)
if (player_turn()):
print ('Congratulations! Your are winner !!')
break;
print ('-' * 20)
print('computer's turn')
show_detail(computerNums, computerHints)
if (computer_turn()):
print ('Computer wins this game !!')
break;
count += 1
應用實例:猜數字遊戲 11/11
91
92.
程式中若要使用math套件的sqrt函式,又要使用squareRoot別名,則
下列匯入敘述何者正確?
A. from math.sqrt as squareRoot
B. from math import sqrt as squareRoot
C. import math.sqrt as squareRoot
D. import sqrt from math as squareRoot
自我評量 1/9
92
93.
在程式中要從10~20之間隨機產生⼀整數,下列何者正確?
A. random.randint(10, 20)
B. random.randrange(10, 20, 1)
C. random.randint(10, 21)
D. random.randrange(11, 21, 1)
自我評量 2/9
93
94.
在程式中要從0.0~1.0之間隨機產生⼀浮點數,下列何者正確?
A. random.randint(0, 1)
B. random.randrange(0.0, 1.0)
C. random.random(0, 1)
D. random.random()
自我評量 3/9
94
95.
要隨機產生⼀個整數,但這個整數必須符合下列條件
數字是3的倍數
最小數是9
最大數是99
A. import random as R
print(R.randint(3, 33) * 3)
B. from random import *
print(randint(3, 32) * 3)
C. from random import randrange
print(randrange(3, 99, 3))
D. from random import randrange as rnd
print(rnd(3, 99, 3))
自我評量 4/9
95
96.
自我評量 5/9
設計⼀函式,傳入引數n為浮點數,回傳值為正整數值,則函式會使用
到下列那些敘述?
A. math.abs(n)
B. math.fabs(n)
C. math.round(n)
D. math.float(n)
E. math.floor(n)
F. math.ceil(n)
G. math.fmod(n)
H. math.int(n)
96
97.
串列 A = [1,3,9,2,5,8,4,9,6,7],呼叫 f(A, 10) 後,回傳值為何?
def f(A, n):
index = 0
for i in range(n):
if A[i] >= A[index]:
index = i
return index
1. 1
2. 2
3. 7
4. 9
自我評量 6/9
97
Los recortes son una forma práctica de recopilar diapositivas importantes para volver a ellas más tarde. Ahora puedes personalizar el nombre de un tablero de recortes para guardar tus recortes.
Crear un tablero de recortes
Compartir esta SlideShare
¿Odia los anuncios?
Consiga SlideShare sin anuncios
Acceda a millones de presentaciones, documentos, libros electrónicos, audiolibros, revistas y mucho más. Todos ellos sin anuncios.
Oferta especial para lectores de SlideShare
Solo para ti: Prueba exclusiva de 60 días con acceso a la mayor biblioteca digital del mundo.
La familia SlideShare crece. Disfruta de acceso a millones de libros electrónicos, audiolibros, revistas y mucho más de Scribd.
Parece que tiene un bloqueador de anuncios ejecutándose. Poniendo SlideShare en la lista blanca de su bloqueador de anuncios, está apoyando a nuestra comunidad de creadores de contenidos.
¿Odia los anuncios?
Hemos actualizado nuestra política de privacidad.
Hemos actualizado su política de privacidad para cumplir con las cambiantes normativas de privacidad internacionales y para ofrecerle información sobre las limitadas formas en las que utilizamos sus datos.
Puede leer los detalles a continuación. Al aceptar, usted acepta la política de privacidad actualizada.