Python 簡介
出自KMU Wiki
(修訂版本間差異)
| 在2008年12月3日 (三) 19:32所做的修訂版本 (編輯) Cch (對話 | 貢獻) (→練習) ←上一個 |
在2008年12月3日 (三) 19:34所做的修訂版本 (編輯) (撤銷) Mcdlee (對話 | 貢獻) (→參考解答mcdlee) 下一個→ |
||
| 第42行: | 第42行: | ||
| ====參考解答mcdlee==== | ====參考解答mcdlee==== | ||
| + | <pre> | ||
| + | #!/usr/bin/env python | ||
| + | import math | ||
| + | import time | ||
| + | |||
| + | x = int(raw_input("enter a number\n")) | ||
| + | start = time.clock() | ||
| + | |||
| + | a = 2 | ||
| + | prime = [2] | ||
| + | def say_yes(): | ||
| + | print a, 'is a prime number' | ||
| + | |||
| + | while a <= x: | ||
| + | if a in prime: | ||
| + | say_yes() | ||
| + | for item in prime: | ||
| + | b = a % item | ||
| + | if b == 0: | ||
| + | break | ||
| + | else: | ||
| + | say_yes() | ||
| + | prime.append(a) | ||
| + | a = a + 1 | ||
| + | amount = len(prime) | ||
| + | |||
| + | print 'There is', amount, 'prime number below', x | ||
| + | |||
| + | </pre> | ||
| ====參考解答sevenstar==== | ====參考解答sevenstar==== | ||
在2008年12月3日 (三) 19:34所做的修訂版本
本條目所指的 Python 是 Python 程式語言
目錄 |
概覽
A Byte of Python 對 Python 的簡介(中譯版)
根據 2008 年 11 月 TIOBE Programming Community Index,Python 的普及率在全世界排名第 6
免費電子書
下載
參考資料
練習
檢查一個數是否為質數
- 題目
由使用者輸入一個整數,然後判斷其是否為質數。
參考解答jai166
參考解答mcdlee
#!/usr/bin/env python
import math
import time
x = int(raw_input("enter a number\n"))
start = time.clock()
a = 2
prime = [2]
def say_yes():
print a, 'is a prime number'
while a <= x:
if a in prime:
say_yes()
for item in prime:
b = a % item
if b == 0:
break
else:
say_yes()
prime.append(a)
a = a + 1
amount = len(prime)
print 'There is', amount, 'prime number below', x
參考解答sevenstar
參考解答cch
#!/usr/local/bin/python
# This program tests wether an integer is a prime
import sys
import math
import string
print 'This program tests wether an integer is a prime'
while 1 :
sys.stdout.write('Please input an integer: ')
s = raw_input()
n = string.atol(s)
ub = math.sqrt(n) + 1
is_prime = 1
f = 2
while f < ub :
if n % f == 0:
is_prime = 0
print n, ' has a factor ', f
break
else :
f = f + 1
if is_prime == 1 :
print n, ' is a prime'
else :
print n, ' is not a prime'
附註:
- FreeBSD 上有一支程式 primes (/usr/games/primes) 可幫我們列出質數以供測試,如: primes 100 200 可列出 100 到 200 間的質數
- 根據 維基百科英文版對質數的介紹,有一個 polynomial time 的演算法 AKS
產生個人化訊息
- 題目
假設今天有一個名單如下:
99001001 趙一忠 99001024 錢二孝 99002015 孫三仁 99051273 李四愛 99181730 周五信
如何寫一支程式產生如下訊息:
親愛的 {姓名} 同學,
您學校的 e-mail 信箱是 u{學號}@kmu.edu.tw
