æ許æ¨å¸¸å¸¸è½å°ç¨å¼çèææå°ãç©ä»¶ãããç©ä»¶åãããç©ä»¶å°åã...ï¼æç¥éæ¨å¾æ³ç½µä»å®
ç·ï¼ä½é確實æ¯å¯«ç¨å¼ä¸åå¾éè¦çè§å¿µèæè½ãèç´æ¥è·Pythonçåå¸è
è¨è«ãç©ä»¶å°åãï¼é£ä¹åªæè®åå¸è
ãå¾å
¥éå°æ¾æ£ããåä¹ï¼ä¸å¦å
æ¾ä¸éäºåè©è§£éï¼å
ä¾ç解çºä½é樣ç寫ç¨å¼æ¹æ³æå¾ææçå§ï¼
# pythonä¸ def functionçåºæ¬çµæ§
def æ¹æ³å稱(æ¹æ³æéè®æ¸):
æ¹æ³å
§å®¹
å¦ææ¨éè¨å¾è¦æ麼ç®å¾æ£ï¼ä½å¦æä½ å¿äºï¼é£é裡ç´æ¥åè¨´ä½ å ¬å¼ï¼ä¸è¦è±æéå°æ³¨å¨æ¸å¸ä¸ï¼éä¸æ¯éé»ï¼
10 x 9 x 8 x .....x 1
 ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄
(8 x 7 x 6 x... x 1) x (2 x 1)
æ¸å¸å¼ç寫æ³ï¼
10!
 ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄
(10-2)! * 2!
æåå¨è¿´åforç課ç¨ä¸ç¥éé種é£çºåçæ¸åæé©å使ç¨forè¿´åäºï¼å æ¤åå¥å°ä¸åæ¸åç®åºä¾ä»¥å¾åè¨ç®ï¼pythonç¨å¼ç¢¼å¦ä¸ï¼ã
# åé¡ï¼ç¨ç¨å¼å¯¦ç¾æ©çãcçXåYã
# 10!/(10-2)! * 2!
#----- åæ³ç
é¼å¯«æ³ -----
x = 10
y = 2
# è¨ç®10!
count1 = 1
for i in range(1, x+1):
count1 = count1 * i
# è¨ç®(10-2)!
count2 = 1
for i in range(1, x-y+1):
count2 = count2 * i
# è¨ç®2!
count3 = 1
for i in range(1, y+1):
count3 = count3 * i
#ç¢åºè¨ç®çµæ
c = count1 / (count2 * count3)
print(c)
以ä¸çæ令æç¢åºä»¥ä¸ççµæï¼
45.0
éåçµæéç¶æ¯æåè¦çï¼ä¸é寫å®ä¹æ»¿èº«å¤§æ±ãç´°å¿çæ¨æ注æå°ä¸é¢çä¸åè¿´åä¼¼ä¹é½é·å¾å¾åï¼ä½åæäºç´°å¾®çä¸ä¸æ¨£ãé樣éè¤çå·¥ä½æ該è¦äº¤çµ¦é»è ¦ï¼æ麼ææ¯è®äººå·¥ä¾èçå¢ï¼
æåå°ååçä¸åè¿´åæ´çæ以ä¸çdefæ¹æ³ï¼
def factorial(n):
"""
åæ¸nï¼æ¬²è¨ç®é層çå°¾æ¸
ç¯ä¾ï¼è¨ç®10!ï¼n輸å
¥10
"""
count = 1
for i in range(1, n+1):
count = count * i
return count
ç¨å¼å §å®¹ | 說æ |
---|---|
factorial | èªè¨çæ¹æ³å稱ï¼è·è®æ¸ä¸æ¨£å¯ä»¥é¨æå½åï¼åªè¦ä¸è¦ä½¿ç¨å°ä¿çåå å³å¯ã |
n | æ¤æ¹æ³ãå §é¨ã使ç¨çè®æ¸ï¼å¨ä½¿ç¨æ¤æ¹æ³æå¿ é è¦å³çµ¦nä¸åæ¸å¼ï¼ènä¹åªæå¨æ¹æ³å §ä½¿ç¨ï¼å¨æ¹æ³å¤ç¡æ³ä½¿ç¨ |
""" | å¾æ顯就æ¯å¯«è¨»è§£ï¼å»ºè°å¨å»ºç«æ¹æ³æè¦æ寫註解çç¿æ £ï¼æ¹ä¾¿å¾çºçç¶è·ãèæ¹æ³å §ç註解è³å°è¦ï¼éåæ¹æ³å¨å¹¹åï¼éè¦ä»éº¼åæ¸ï¼ï½ |
return | åå³å¼ï¼ä¹å¯ä»¥ä¸åå³ï¼éè¦çæ¹æ³çè¨è¨èç®ç |
èå¼å«éåæ¹æ³å·²ä¹å¾ç°¡å®ï¼ç´æ¥è¼¸å ¥ãæ¹æ³å稱ï¼ï¼ãå³å¯ï¼èå¨æ¤æ¬¡èä¾ä¸factorialæ¹æ³éè¦ä¸ånè®æ¸ï¼å æ¤å¨æ¬èä¸éè¦å³éä¸åæ¸å給ä»ï¼èéåæ¸åä¹æ¯æåæ³è¦é²è¡é層è¨ç®çæ¸åï¼
factorial(5) # è¨ç®5!
å æ¤é次çæåçµååé¡ï¼ä¹å¯ä»¥å¯«æé樣ï¼
x = 10
y = 2
# é層è¨ç®æ©
def factorial(n):
"""
åæ¸nï¼æ¬²è¨ç®é層çå°¾æ¸
ç¯ä¾ï¼è¨ç®10!ï¼n輸å
¥10
"""
count = 1
for i in range(1, n+1):
count = count * i
return count
c = factorial(x) / (factorial(x-y) * factorial(y))
print(c)
以ä¸çæ令æç¢åºä»¥ä¸ççµæï¼
45.0
ææåå¼å«æ¹æ³æå¯è½æå¿è¨è¼¸å ¥è®æ¸ï¼åæè éåæ¹æ³çè®æ¸å¤§é¨åçæéé½æ¯ä¸æ¨£çï¼åªæå°æ¸çä¾å¤çæ³éè¦èª¿æ´æ¤è®æ¸ï¼é£æ¯æ¬¡å¼å«è©²æ¹æ³é½è¦æå®è®æ¸è®æä¸ä»¶å¾éº»ç ©çäºæ ï¼ä½åä¸è½ç´æ¥å¯«æ»ï¼è©²æ麼辦å¢ï¼å ¶å¯¦å¯ä»¥æ¹æ以ä¸çæ¹å¼ï¼å¨æ¹æ³çåæ¸nä¸æå®5ï¼
def factorial(n = 5): # é è¨åæ¸5
"""
åæ¸nï¼æ¬²è¨ç®é層çå°¾æ¸
ç¯ä¾ï¼è¨ç®10!ï¼n輸å
¥10
"""
count = 1
for i in range(1, n+1):
count = count * i
return count
factorial() # æ²çµ¦nå°±é è¨næ¯5ï¼è¨ç®5!
以ä¸çæ令æç¢åºä»¥ä¸ççµæï¼
120.0
å¨ä¸éå§å¯«defæ¹æ³çæåè ¦çæéè¦è½ä¸ä¸ï¼è¦èæ ®ä»éº¼æ±è¥¿è¦è¨å®æè®æ¸ï¼æå¾åè¦åå³ä»éº¼æ±è¥¿ãå¼å¾ä¸æçæ¯pythonçåå³returnå¯ä»¥åå³å¤åå¼ï¼éå¨å ¶ä»ç¨å¼èªè¨ä¸æ¯ç¡æ³åå°çï¼å¦ä»¥ä¸ç¨å¼ç¢¼ç¯ä¾ï¼
def notThing():
return 10, 20
# ç¨aè·bå
©åè®æ¸ä¾æ¥æ¶
a, b = notThing()
print(a)
print(b)
以ä¸çæ令æç¢åºä»¥ä¸ççµæï¼
10
20
作者:楊超霆 行銷搬進大程式 創辦人