2016年9月19日 星期一

程式集訓 A009:1-100 質數判別

#coding=utf8

#程式集訓 A009:1-100 質數判別
'''
   /*描述 輸入一個正整數,如果是質數,則輸出 Yes,如果不是,則輸出 No。
'''

#==========================
print("1-100 質數判別")

for i in range (2,101):
     cnt=0
     for j in range (2,i+1):
       if (i%j==0) :
          cnt=cnt+1
     if (cnt==1):   #只被整除1次就是質數
         print(i,"為質數")
#===========================        

Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
================= RESTART: D:/程式語言 Python 入門/程式集訓/A009-1.py =================
1-100 質數判別
2 為質數
3 為質數
5 為質數
7 為質數
11 為質數
13 為質數
17 為質數
19 為質數
23 為質數
29 為質數
31 為質數
37 為質數
41 為質數
43 為質數
47 為質數
53 為質數
59 為質數
61 為質數
67 為質數
71 為質數
73 為質數
79 為質數
83 為質數
89 為質數
97 為質數
>>>      
     

程式集訓 A009:質數判別

#coding=utf8

#程式集訓 A009:質數判別
'''
       /*
描述 輸入一個正整數,如果是質數,則輸出 Yes,如果不是,則輸出 No。
'''
#==========================
def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass

    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass

    return False
#==========================

n=1
while n!=0:
  a=int(input("輸入正整數  A="))
  if (is_number(a) != True) :
     print ('這是不合法的輸入.  請再輸入一次...')
     n=1
  else:
     A=int(a)
     n=0  
#==========================
x=0
for i in range (2,A+1):
     x=A%i
     if (A==i) :
         print(A,"為質數")
         break
     if (x==0) :
         print(A,"不是質數")
         break            
     
     



Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
================== RESTART: D:/程式語言 Python 入門/程式集訓/A009.py ==================
輸入正整數  A=12
12 不是質數
>>> 
================== RESTART: D:/程式語言 Python 入門/程式集訓/A009.py ==================
輸入正整數  A=3
3 為質數
>>> 
================== RESTART: D:/程式語言 Python 入門/程式集訓/A009.py ==================
輸入正整數  A=9
9 不是質數
>>> 

程式集訓 A008:九九乘法表


#coding=utf8

#程式集訓 A008:九九乘法表
'''
         A008:九九乘法表  程式印出九九乘法表!
'''
for i in range (1,10):
  for j in range (1,10):
     print('{:1d}'.format(i),"*",'{:1d}'.format(j),"=",'{:2d}'.format(i*j) ,end=" ,")
  print()
#========================
   
     


================== RESTART: D:/程式語言 Python 入門/程式集訓/A008.py ==================
1 * 1 =  1 ,1 * 2 =  2 ,1 * 3 =  3 ,1 * 4 =  4 ,1 * 5 =  5 ,1 * 6 =  6 ,1 * 7 =  7 ,1 * 8 =  8 ,1 * 9 =  9 ,
2 * 1 =  2 ,2 * 2 =  4 ,2 * 3 =  6 ,2 * 4 =  8 ,2 * 5 = 10 ,2 * 6 = 12 ,2 * 7 = 14 ,2 * 8 = 16 ,2 * 9 = 18 ,
3 * 1 =  3 ,3 * 2 =  6 ,3 * 3 =  9 ,3 * 4 = 12 ,3 * 5 = 15 ,3 * 6 = 18 ,3 * 7 = 21 ,3 * 8 = 24 ,3 * 9 = 27 ,
4 * 1 =  4 ,4 * 2 =  8 ,4 * 3 = 12 ,4 * 4 = 16 ,4 * 5 = 20 ,4 * 6 = 24 ,4 * 7 = 28 ,4 * 8 = 32 ,4 * 9 = 36 ,
5 * 1 =  5 ,5 * 2 = 10 ,5 * 3 = 15 ,5 * 4 = 20 ,5 * 5 = 25 ,5 * 6 = 30 ,5 * 7 = 35 ,5 * 8 = 40 ,5 * 9 = 45 ,
6 * 1 =  6 ,6 * 2 = 12 ,6 * 3 = 18 ,6 * 4 = 24 ,6 * 5 = 30 ,6 * 6 = 36 ,6 * 7 = 42 ,6 * 8 = 48 ,6 * 9 = 54 ,
7 * 1 =  7 ,7 * 2 = 14 ,7 * 3 = 21 ,7 * 4 = 28 ,7 * 5 = 35 ,7 * 6 = 42 ,7 * 7 = 49 ,7 * 8 = 56 ,7 * 9 = 63 ,
8 * 1 =  8 ,8 * 2 = 16 ,8 * 3 = 24 ,8 * 4 = 32 ,8 * 5 = 40 ,8 * 6 = 48 ,8 * 7 = 56 ,8 * 8 = 64 ,8 * 9 = 72 ,
9 * 1 =  9 ,9 * 2 = 18 ,9 * 3 = 27 ,9 * 4 = 36 ,9 * 5 = 45 ,9 * 6 = 54 ,9 * 7 = 63 ,9 * 8 = 72 ,9 * 9 = 81 ,
>>> 

2016年9月18日 星期日

程式集訓 G008:小寫轉大寫

 #coding=utf8

#程式集訓 G008:小寫轉大寫
'''
G008:小寫轉大寫
題目:   (G008) 小寫轉大寫 : 輸入一英文連字串,將所有英文字母轉成大寫印出。
str.upper() 將 str 的英文字母都改成大寫
'''
a=str(input("請輸入一英文連字串:"))
b=str.upper(a)
print("其大寫字串為:",b)


================== RESTART: D:/程式語言 Python 入門/程式集訓/G008.py ==================
請輸入一英文連字串:If you're on a Unix terminal, you can print "\a" to get a terminal bell:
其大寫字串為: IF YOU'RE ON A UNIX TERMINAL, YOU CAN PRINT "\A" TO GET A TERMINAL BELL:
>>> 


源自於
http://pydoing.blogspot.tw/2011/03/python-stringtype.html

字串 (string) 屬於不可變 (immutable) 的序列 (sequence) 型態,可進行以下序列通用的計算

計算描述
x in s判斷 x 是否在 s 中
x not in s判斷 x 是否不在 s 中
s + t連接 s 及 t
s * n, n * s將 s 重複 n 次連接 s 本身
s[i]取得索引值 i 的元素
s[i:j]取得索引值 i 到 j 的子序列
s[i:j:k]取得索引值 i 到 j ,間隔 k 的子序列
len(s)回傳 s 的元素個數
min(s)回傳 s 中的最小值
max(s)回傳 s 中的最大值
s.index(i)取得 s 中第一次出現 i 的索引值
s.count(i)累計 s 中 i 出現的個數


字串型態有以下的方法 (method)

方法描述
str.capitalize()回傳將 str 改成首字母大寫,其餘字母小寫的字串
str.center(width[, fillchar])回傳一個將 str 設置字串中央,長度 width 的新字串, fillchar 為填充字元,預設為空格
str.count(sub[, start[, end]])計算 sub 出現的次數, start 為起始計算索引值, end 為結束索引值
str.encode(encoding="utf-8", errors="strict")回傳 encoding 版本的 bytes 物件
str.endswith(suffix[, start[, end]])判斷 str 是否以 suffix 結尾
str.expandtabs([tabsize])將 tab 符號以 tabsize 的空格數替換
str.find(sub[, start[, end]])回傳 sub 第一次出現的索引值
str.format(*args, **kwargs)進行格式化字串運算
str.index(sub[, start[, end]])回傳 sub 第一次出現的索引值
str.isalnum()判斷字串中的字元是否都是字母或數字
str.isalpha()判斷字串中的字元是否都是字母
str.isdecimal()判斷字串中所有字元是否是十進位數字
str.isdigit()判斷字串中所有字元是否是數字
str.isidentifier()判斷字串是否可作為合法的識別字
str.islower()判斷字串中所有字母字元是否都是小寫字母
str.isnumeric()判斷字串中所有字元是否是數字
str.isprintable()判斷字串中所有字元是否都屬於可見字元
str.isspace()判斷字串是否為空格字元
str.istitle()判斷字串是否適合當作標題
str.isupper()判斷字串中所有字母字元是否都是大寫字母
str.join(iterable)回傳將 str 連結 iterable 各元素的字串
str.ljust(width[, fillchar])回傳將 str 在寬度 width 向左對齊的字串, fillchar 為填充字元,預設為空格
str.lower()將 str 的英文字母都改成小寫
str.lstrip([chars])回傳將 str 左邊具有 chars 字元去除的拷貝版本, chars 預設為空格符號
static str.maketrans(x[, y[, z]])回傳 x 與 y 配對的 Unicode 編碼字典,若有提供 z , z 中的字元會跟 None 配對
str.partition(sep)以 sep 分割 str 為三個部份,結果回傳具有三個子字串的序對
str.replace(old, new[, count])將 str 中的 old 子字串以 new 代換
str.rfind(sub[, start[, end]])尋找最右邊的 sub ,也就是索引值最大的 sub
str.rindex(sub[, start[, end]])尋找最右邊的 sub ,也就是索引值最大的 sub
str.rjust(width[, fillchar])回傳將 str 在寬度 width 向右對齊的字串, fillchar 為填充字元,預設為空格
str.rpartition(sep)以 sep 從最右端分割 str 為三個部份,結果回傳具有三個子字串的序對
str.rsplit([sep[, maxsplit]])將 str 從最右端以 sep 分割成子字串,回傳儲存子字串的串列, maxsplit 為子字串最多的數量
str.rstrip([chars])從 str 的最右端中移除 chars 字元,預設為空白字元
str.split([sep[, maxsplit]])將 str 以 sep 分割成子字串,回傳儲存子字串的串列, maxsplit 為子字串最多的數量
str.splitlines([keepends])將 str 以新行符號分割成子字串,回傳儲存子字串的串列
str.startswith(prefix[, start[, end]])判斷 str 是否以 prefix 開頭
str.strip([chars])從 str 中移除 chars 字元,預設為空白字元
str.swapcase()將 str 中的英文字母進行大小寫轉換
str.title()將 str 轉換成作為標題的字串
str.translate(map)將 str 中的字元以 map 中配對的字元轉換
str.upper()將 str 的英文字母都改成大寫
str.zfill(width)回傳以 0 塞滿 width 的新字串

程式集訓 G008:小寫轉大寫

 #coding=utf8

#程式集訓 G008:小寫轉大寫
'''
G008:小寫轉大寫
題目:   (G008) 小寫轉大寫 : 輸入一英文連字串,將所有英文字母轉成大寫印出。
str.upper() 將 str 的英文字母都改成大寫
'''
a=str(input("請輸入一英文連字串:"))
b=str.upper(a)
print("其大寫字串為:",b)


================== RESTART: D:/程式語言 Python 入門/程式集訓/G008.py ==================
請輸入一英文連字串:If you're on a Unix terminal, you can print "\a" to get a terminal bell:
其大寫字串為: IF YOU'RE ON A UNIX TERMINAL, YOU CAN PRINT "\A" TO GET A TERMINAL BELL:
>>> 


源自於
http://pydoing.blogspot.tw/2011/03/python-stringtype.html

字串 (string) 屬於不可變 (immutable) 的序列 (sequence) 型態,可進行以下序列通用的計算

計算描述
x in s判斷 x 是否在 s 中
x not in s判斷 x 是否不在 s 中
s + t連接 s 及 t
s * n, n * s將 s 重複 n 次連接 s 本身
s[i]取得索引值 i 的元素
s[i:j]取得索引值 i 到 j 的子序列
s[i:j:k]取得索引值 i 到 j ,間隔 k 的子序列
len(s)回傳 s 的元素個數
min(s)回傳 s 中的最小值
max(s)回傳 s 中的最大值
s.index(i)取得 s 中第一次出現 i 的索引值
s.count(i)累計 s 中 i 出現的個數


字串型態有以下的方法 (method)

方法描述
str.capitalize()回傳將 str 改成首字母大寫,其餘字母小寫的字串
str.center(width[, fillchar])回傳一個將 str 設置字串中央,長度 width 的新字串, fillchar 為填充字元,預設為空格
str.count(sub[, start[, end]])計算 sub 出現的次數, start 為起始計算索引值, end 為結束索引值
str.encode(encoding="utf-8", errors="strict")回傳 encoding 版本的 bytes 物件
str.endswith(suffix[, start[, end]])判斷 str 是否以 suffix 結尾
str.expandtabs([tabsize])將 tab 符號以 tabsize 的空格數替換
str.find(sub[, start[, end]])回傳 sub 第一次出現的索引值
str.format(*args, **kwargs)進行格式化字串運算
str.index(sub[, start[, end]])回傳 sub 第一次出現的索引值
str.isalnum()判斷字串中的字元是否都是字母或數字
str.isalpha()判斷字串中的字元是否都是字母
str.isdecimal()判斷字串中所有字元是否是十進位數字
str.isdigit()判斷字串中所有字元是否是數字
str.isidentifier()判斷字串是否可作為合法的識別字
str.islower()判斷字串中所有字母字元是否都是小寫字母
str.isnumeric()判斷字串中所有字元是否是數字
str.isprintable()判斷字串中所有字元是否都屬於可見字元
str.isspace()判斷字串是否為空格字元
str.istitle()判斷字串是否適合當作標題
str.isupper()判斷字串中所有字母字元是否都是大寫字母
str.join(iterable)回傳將 str 連結 iterable 各元素的字串
str.ljust(width[, fillchar])回傳將 str 在寬度 width 向左對齊的字串, fillchar 為填充字元,預設為空格
str.lower()將 str 的英文字母都改成小寫
str.lstrip([chars])回傳將 str 左邊具有 chars 字元去除的拷貝版本, chars 預設為空格符號
static str.maketrans(x[, y[, z]])回傳 x 與 y 配對的 Unicode 編碼字典,若有提供 z , z 中的字元會跟 None 配對
str.partition(sep)以 sep 分割 str 為三個部份,結果回傳具有三個子字串的序對
str.replace(old, new[, count])將 str 中的 old 子字串以 new 代換
str.rfind(sub[, start[, end]])尋找最右邊的 sub ,也就是索引值最大的 sub
str.rindex(sub[, start[, end]])尋找最右邊的 sub ,也就是索引值最大的 sub
str.rjust(width[, fillchar])回傳將 str 在寬度 width 向右對齊的字串, fillchar 為填充字元,預設為空格
str.rpartition(sep)以 sep 從最右端分割 str 為三個部份,結果回傳具有三個子字串的序對
str.rsplit([sep[, maxsplit]])將 str 從最右端以 sep 分割成子字串,回傳儲存子字串的串列, maxsplit 為子字串最多的數量
str.rstrip([chars])從 str 的最右端中移除 chars 字元,預設為空白字元
str.split([sep[, maxsplit]])將 str 以 sep 分割成子字串,回傳儲存子字串的串列, maxsplit 為子字串最多的數量
str.splitlines([keepends])將 str 以新行符號分割成子字串,回傳儲存子字串的串列
str.startswith(prefix[, start[, end]])判斷 str 是否以 prefix 開頭
str.strip([chars])從 str 中移除 chars 字元,預設為空白字元
str.swapcase()將 str 中的英文字母進行大小寫轉換
str.title()將 str 轉換成作為標題的字串
str.translate(map)將 str 中的字元以 map 中配對的字元轉換
str.upper()將 str 的英文字母都改成大寫
str.zfill(width)回傳以 0 塞滿 width 的新字串

程式集訓 F010:溢出字元-beep

#coding=utf8

#程式集訓  F010:溢出字元-beep
'''
題目:(F010) 溢出字元-beep : 輸出相同的字串及聲音

Escape Sequence Meaning
\newline Ignored
\\ Backslash (\)
\' Single quote (')
\" Double quote (")
\a ASCII Bell (BEL)
\b ASCII Backspace (BS)
\f ASCII Formfeed (FF)
\n ASCII Linefeed (LF)
\r ASCII Carriage Return (CR)
\t ASCII Horizontal Tab (TAB)
\v ASCII Vertical Tab (VT)
\ooo ASCII character with octal value ooo
'''
#\xhh.... ASCII character with hex value hh....

#If you're on a Unix terminal, you can print "\a" to get a terminal bell:
def beep():
      print ("\a")

for i in range (0,10):
    beep()
#=======================================
import winsound         # for sound
import time             # for sleep

Freq = 2500 # Set Frequency To 2500 Hertz
Dur = 1000 # Set Duration To 1000 ms == 1 second
winsound.Beep(Freq,Dur)
time.sleep(0.25)        # in seconds (0.25 is 250ms)

winsound.Beep(440, 250) # frequency, duration
time.sleep(0.25)        # in seconds (0.25 is 250ms)

winsound.Beep(600, 250)
time.sleep(0.25)

程式集訓 F007:輸入ASCII及字元顯示

 #coding=utf8

#程式集訓  F007:輸入ASCII及字元顯示
'''
題目:
       (F007) 輸入ASCII及字元顯示 : 輸入一個ASCII數字,
       輸出數所代表之字元及ASCII碼,再輸出ASCII表上的下一個字元及其ASCII碼

'''
#  ord('A')=65
#  chr(65) ='A'
while True:
     try:
        a=int (input("請輸入一個字元 :"))
        break 
     except ValueError:
        print ('這是不合法的輸入.  請再輸入一次...')
        continue


a2=chr(a)      
a3=ord(a2)

b=int(a+1)
b2=chr(b)
b3=ord(b2)

print("字元及ASCII碼 ==> ",a2,a3,hex(a3))
print("再輸出ASCII表上的下一個字元及其ASCII碼 ==> ",b2,b3,hex(b3))


================== RESTART: D:/程式語言 Python 入門/程式集訓/F007.py ==================
請輸入一個字元 :65
字元及ASCII碼 ==>  A 65 0x41
再輸出ASCII表上的下一個字元及其ASCII碼 ==>  B 66 0x42
>>> 
================== RESTART: D:/程式語言 Python 入門/程式集訓/F007.py ==================
請輸入一個字元 :1
字元及ASCII碼 ==>   1 0x1
再輸出ASCII表上的下一個字元及其ASCII碼 ==>   2 0x2
>>> 

程式集訓 F006:字元輸入及顯示

#coding=utf8

#程式集訓  F006:字元輸入及顯示
'''
  F006:字元輸入及顯示

題目:

         字元輸入及顯示 : 輸入一個字元,
         輸出其字元及ASCII碼,再輸出ASCII表上的下一個字元及其ASCII碼
'''
#  ord('A')=65
#  chr(65) ='A'

a=str (input("請輸入一個字元 :"))
a2=ord(a)      
a3=chr(a2)

b=int(a2+1)
b3=chr(b)
b2=ord(b3)

print("字元及ASCII碼 ==> ",a3,a2,hex(a2))
print("再輸出ASCII表上的下一個字元及其ASCII碼 ==> ",b3,b2,hex(b2))


================== RESTART: D:/程式語言 Python 入門/程式集訓/F006.py ==================
請輸入一個字元 :a
字元及ASCII碼 ==>  a 97 0x61
再輸出ASCII表上的下一個字元及其ASCII碼 ==>  b 98 0x62
>>> 

2016年9月17日 星期六

程式集訓 A014: 次方求餘

#coding=utf8

#程式集訓 A014: 次方求餘
'''
    A014 次方求餘

輸入三個正整數 n p d,輸出(n^p)%d,即 n 的 p次方 對 d的餘數。

這題看似簡單,卻包含一個數學陷阱。簡單的求餘數不難,
但是這題有個小陷阱,就是"次方",取次方可能會出現極大數字,造成溢位。
因此利用迴圈處理次方的運算,每次迴圈當中,持續將每次增加的底數去
餘數,之後再取一次餘數,利用這個方式避免溢位。

'''

print("輸入三個正整數 n p d,輸出(n^p)%d,即 n 的 p次方 對 d的餘數。")
while True:
      try:
        n,p,d=(input("請輸入 輸入三個正整數 n p d : " ).split())
        n=int(n)
        p=int(p)
        d=int(d)
        break
              
      except ValueError:
         print ('這是不合法的輸入.  請再輸入一次...')
         continue

      if (d==0) :
         break

ans = int(1)
for i in range(1,p+1):
   ans = ans*n
   ans %= d

print("(",n,"^",p,")%",d,"  餘數為",'{:6d}'.format(ans))

#=========================================
     


輸入三個正整數 n p d,輸出(n^p)%d,即 n 的 p次方 對 d的餘數。
請輸入 輸入三個正整數 n p d : 59 89 80
( 59 ^ 89 )% 80   餘數為     59
>>> 

程式集訓 M90H063: 二次函數之極小值


#coding=utf8

#程式集訓 M90H063: 二次函數之極小值
'''
    M90H063: 二次函數之極小值
// 一元二次方程式: f(x) = a*x^2 + b*x + c
// 當 x = -b/2*a 時有最小值

'''
while True:
      try:
        a,b,c=(input("請輸入 AX^2+BX+C=0 的 A B C ?" ).split())
        a=float(a)
        b=float(b)
        c=float(c)
        break
              
      except ValueError:
         print ('這是不合法的輸入.  請再輸入一次...')
         continue

x = -b/(2*a)
print("當 x=",'{:6.2f}'.format(x),end="")
min1= (a*(x**2)) + b*x + c
print(" 有極小值為",'{:6.2f}'.format(min1))
#=========================================

     

================= RESTART: D:/程式語言 Python 入門/程式集訓/M90H063.py =================
請輸入 AX^2+BX+C=0 的 A B C ?12 3 2
當 x=  -0.12有極小值為   1.81
>>>

程式集訓 M90H028: 平面幾何:中點公式


#coding=utf8

#程式集訓 M90H028: 平面幾何:中點公式
'''
    M90H028: 平面幾何:中點公式
'''
initial_value = 0
list_length = 4
sample_list1 = [initial_value]*list_length
i=0
j=0
while i<=1:
    while True:
      try:
        print("請輸入第",i+1,end="")
        m1,m2=(input("點(x,y)的x值及y值:   ").split())
        m1=float(m1)
        m2=float(m2)
        if (m1 >= 0  and m2 >=0):
            break     
        else:
            print ('這是不合法的輸入.  請再輸入一次...')
            continue            
      except ValueError:
         print ('這是不合法的輸入.  請再輸入一次...')
         continue
    i=i+1
    sample_list1[j]=float(m1)
    j=j+1
    sample_list1[j]=float(m2)
    j=j+1
    print(sample_list1)
  
x= (sample_list1[0]+sample_list1[2])/2
y= (sample_list1[1]+sample_list1[3])/2
print("中點為(",'{:6.2f}'.format(x),"),(",'{:6.2f}'.format(y),")")
#=========================================

     

================= RESTART: D:/程式語言 Python 入門/程式集訓/M90H028.py =================
請輸入第 1點(x,y)的x值及y值:   12 23
[12.0, 23.0, 0, 0]
請輸入第 2點(x,y)的x值及y值:   34 45
[12.0, 23.0, 34.0, 45.0]
中點為(  23.00 ),(  34.00 )
>>> 

程式集訓 M90H023: 平面幾何:三角形重心


#coding=utf8

#程式集訓 M90H023: 平面幾何:三角形重心
'''
    M90H023: 平面幾何:三角形重心
'''
initial_value = 0
list_length = 6
sample_list1 = [initial_value]*list_length
i=0
j=0
while i<=2:
    while True:
      try:
        print("請輸入第",i+1,end="")
        m1,m2=(input("點(x,y)的x值及y值: (y=999 離開) :  ").split())
        m1=float(m1)
        m2=float(m2)
        if (m1 >= 0  and m2 >=0):
            break     
        else:
            print ('這是不合法的輸入.  請再輸入一次...')
            continue            
      except ValueError:
         print ('這是不合法的輸入.  請再輸入一次...')
         continue
    i=i+1
    sample_list1[j]=float(m1)
    j=j+1
    sample_list1[j]=float(m2)
    j=j+1
    print(sample_list1)
  
x= (sample_list1[0]+sample_list1[2]+sample_list1[4])/3
y= (sample_list1[1]+sample_list1[3]+sample_list1[5])/3
print("重心為(",'{:6.2f}'.format(x),"),(",'{:6.2f}'.format(y),")")
#=========================================

     

================= RESTART: D:/程式語言 Python 入門/程式集訓/M90H023.py =================
請輸入第 1點(x,y)的x值及y值: (y=999 離開) :  12 34
[12.0, 34.0, 0, 0, 0, 0]
請輸入第 2點(x,y)的x值及y值: (y=999 離開) :  23.9 23.5
[12.0, 34.0, 23.9, 23.5, 0, 0]
請輸入第 3點(x,y)的x值及y值: (y=999 離開) :  9.8 7.6
[12.0, 34.0, 23.9, 23.5, 9.8, 7.6]
重心為(  15.23 ),(  21.70 )
>>> 

程式集訓 M90H011: 整數商餘

#coding=utf8

#程式集訓 M90H011: 整數商餘
'''
    M90H011: 整數商餘
'''

i=0
while i==0:
  while True:
    try:
      m,n=(input("請輸入兩整數 m 與 n  (n=999 離開) :  ").split())
      n=int(n)
      if (n > 0 ):
          break     #被除數要 > 0
      else:
          print ('這是不合法的輸入.  請再輸入一次...')
          continue            
    except ValueError:
      print ('這是不合法的輸入.  請再輸入一次...')
      continue

  m=int(m)
  n=int(n)
  print(m ,"除以",n, "之商數為",m//n)
  print(m ,"除以",n, "之餘數為",m%n)

  if (n==999):
     i=1  

#=========================================
     
================= RESTART: D:/程式語言 Python 入門/程式集訓/M90H011.py =================
請輸入兩整數 m 與 n  (n=999 離開) :  123 6
123 除以 6 之商數為 20
123 除以 6 之餘數為 3
請輸入兩整數 m 與 n  (n=999 離開) :  123 999
123 除以 999 之商數為 0
123 除以 999 之餘數為 123
>>> 

2016年9月16日 星期五

程式集訓 F020:計算BMI

#coding=utf8

#程式集訓 F020:計算BMI
'''
               F020:計算BMI
'''
n=0
while n==0:
  while True:
    try:
      c1,c2=(input("請輸入身高(公尺) 與 體重(公斤): (體重999 離開) ").split())
      break
    except ValueError:
      print ('這是不合法的輸入.  請再輸入一次...')
      continue


  if float(c2)==999:     #exit 
     n=1

  m=float(c1)
  kg=float(c2)
  bmi = kg/(m*m)
  print("BMI值=",'{:6.2f}'.format(bmi))

  if( bmi > 25 ):
      print("該減肥了喔!!")
  elif ( bmi <=25 and bmi >= 18.5 ):
      print("標準喔!!")
  else:
      print("太輕喔!!")
  
================== RESTART: D:\程式語言 Python 入門\程式集訓\F020.py ==================
請輸入身高(公尺) 與 體重(公斤): (體重999 離開) 1.78 90
BMI值=  28.41
該減肥了喔!!
請輸入身高(公尺) 與 體重(公斤): (體重999 離開) 1.89 50
BMI值=  14.00
太輕喔!!
請輸入身高(公尺) 與 體重(公斤): (體重999 離開) 1.90 76
BMI值=  21.05
標準喔!!
請輸入身高(公尺) 與 體重(公斤): (體重999 離開) 1 999
BMI值= 999.00
該減肥了喔!!
>>> 

程式集訓 F020:計算BMI

#coding=utf8

#程式集訓 F020:計算BMI
'''
               F020:計算BMI
'''
n=0
while n==0:
  while True:
    try:
      c1,c2=(input("請輸入身高(公尺) 與 體重(公斤): (體重999 離開) ").split())
      break
    except ValueError:
      print ('這是不合法的輸入.  請再輸入一次...')
      continue


  if float(c2)==999:     #exit 
     n=1

  m=float(c1)
  kg=float(c2)
  bmi = kg/(m*m)
  print("BMI值=",'{:6.2f}'.format(bmi))

  if( bmi > 25 ):
      print("該減肥了喔!!")
  elif ( bmi <=25 and bmi >= 18.5 ):
      print("標準喔!!")
  else:
      print("太輕喔!!")
  
================== RESTART: D:\程式語言 Python 入門\程式集訓\F020.py ==================
請輸入身高(公尺) 與 體重(公斤): (體重999 離開) 1.78 90
BMI值=  28.41
該減肥了喔!!
請輸入身高(公尺) 與 體重(公斤): (體重999 離開) 1.89 50
BMI值=  14.00
太輕喔!!
請輸入身高(公尺) 與 體重(公斤): (體重999 離開) 1.90 76
BMI值=  21.05
標準喔!!
請輸入身高(公尺) 與 體重(公斤): (體重999 離開) 1 999
BMI值= 999.00
該減肥了喔!!
>>> 

程式集訓 F020:計算BMI

#coding=utf8

#程式集訓 F020:計算BMI
'''
               F020:計算BMI
'''
n=0
while n==0:
  while True:
    try:
      c1,c2=(input("請輸入身高(公尺) 與 體重(公斤): (體重999 離開) ").split())
      break
    except ValueError:
      print ('這是不合法的輸入.  請再輸入一次...')
      continue


  if float(c2)==999:     #exit 
     n=1

  m=float(c1)
  kg=float(c2)
  bmi = kg/(m*m)
  print("BMI值=",'{:6.2f}'.format(bmi))

  if( bmi > 25 ):
      print("該減肥了喔!!")
  elif ( bmi <=25 and bmi >= 18.5 ):
      print("標準喔!!")
  else:
      print("太輕喔!!")
  
================== RESTART: D:\程式語言 Python 入門\程式集訓\F020.py ==================
請輸入身高(公尺) 與 體重(公斤): (體重999 離開) 1.78 90
BMI值=  28.41
該減肥了喔!!
請輸入身高(公尺) 與 體重(公斤): (體重999 離開) 1.89 50
BMI值=  14.00
太輕喔!!
請輸入身高(公尺) 與 體重(公斤): (體重999 離開) 1.90 76
BMI值=  21.05
標準喔!!
請輸入身高(公尺) 與 體重(公斤): (體重999 離開) 1 999
BMI值= 999.00
該減肥了喔!!
>>> 

程式集訓 F019: 長方形面積

#coding=utf8


#程式集訓 F019: 長方形面積
'''
               F019: 長方形面積
'''
n=0
while n==0:
  while True:
    try:
      c1,c2=(input("請輸入長方形長 與 寬  : (999 離開) ").split())
      break
    except ValueError:
      print ('這是不合法的輸入.  請再輸入一次...')
      continue


  if float(c1)==999:     #exit 
     n=1

  c1=float(c1)
  c2=float(c2)
  c=c1*c2
  print("長方形的長=",'{:6.2f}'.format(c1)," 寬=",'{:6.2f}'.format(c2),"面積=",'{:6.2f}'.format(c))

       
================== RESTART: D:\程式語言 Python 入門\程式集訓\F019.py ==================
請輸入長方形長 與 寬  : (999 離開) 12.9 1221
長方形的長=  12.90  寬= 1221.00 面積= 15750.90
請輸入長方形長 與 寬  : (999 離開) 999 12
長方形的長= 999.00  寬=  12.00 面積= 11988.00

>>> 

   

程式集訓 F001: 兩數相加

#coding=utf8


#程式集訓 F001: 兩數相加
'''
                F001: 兩數相加
'''
n=0
while n==0:
  while True:
    try:
      c1,c2=(input("請輸入 A ,B 二數  : (A=999 離開) ").split())
      break
    except ValueError:
      print ('這是不合法的輸入.  請再輸入一次...')
      continue


  if float(c1)==999:     #exit 
     n=1

  c1=float(c1)
  c2=float(c2)
  c=c1+c2
  print("A=",'{:6.2f}'.format(c1),"與 B=",'{:6.2f}'.format(c2),"相加後",'{:6.2f}'.format(c))

       
   
================== RESTART: D:\程式語言 Python 入門\程式集訓\F001.py ==================
請輸入 A ,B 二數  : (A=999 離開) 12.3 34.5
A=  12.30 與 B=  34.50 相加後  46.80
請輸入 A ,B 二數  : (A=999 離開) 199 7772
A= 199.00 與 B= 7772.00 相加後 7971.00
請輸入 A ,B 二數  : (A=999 離開) 999 0
A= 999.00 與 B=   0.00 相加後 999.00
>>> 

程式集訓 F001: 兩數相加

#coding=utf8


#程式集訓 F001: 兩數相加
'''
                F001: 兩數相加
'''
n=0
while n==0:
  while True:
    try:
      c1,c2=(input("請輸入 A ,B 二數  : (A=999 離開) ").split())
      break
    except ValueError:
      print ('這是不合法的輸入.  請再輸入一次...')
      continue


  if float(c1)==999:     #exit 
     n=1

  c1=float(c1)
  c2=float(c2)
  c=c1+c2
  print("A=",'{:6.2f}'.format(c1),"與 B=",'{:6.2f}'.format(c2),"相加後",'{:6.2f}'.format(c))

       
   
================== RESTART: D:\程式語言 Python 入門\程式集訓\F001.py ==================
請輸入 A ,B 二數  : (A=999 離開) 12.3 34.5
A=  12.30 與 B=  34.50 相加後  46.80
請輸入 A ,B 二數  : (A=999 離開) 199 7772
A= 199.00 與 B= 7772.00 相加後 7971.00
請輸入 A ,B 二數  : (A=999 離開) 999 0
A= 999.00 與 B=   0.00 相加後 999.00
>>> 

程式集訓 G001: 長寬高算體積

#coding=utf8

#程式集訓 G001: 長寬高算體積
'''
               G001: 長寬高算體積
'''
n=0
while n==0:
  while True:
    try:
      c1,c2,c3=(input("請輸入長度 寬度 高度 : (長度999 離開) ").split())
      break
    except ValueError:
      print ('這是不合法的輸入.  請再輸入一次...')
      continue


  if float(c1)==999:     #exit
     print("離開程式")
     n=1

  c1=float(c1)
  c2=float(c2)
  c3=float(c3)
  c=c1*c2*c3
  print("長度=",'{:6.2f}'.format(c1),"公分")
  print("寬度=",'{:6.2f}'.format(c2),"公分")
  print("高度=",'{:6.2f}'.format(c3),"公分")
  print("體積=",'{:6.2f}'.format(c),"立方公分")

================== RESTART: D:\程式語言 Python 入門\程式集訓\G001.py ==================
請輸入長度 寬度 高度 : (長度999 離開) 12 34.7 89.1
長度=  12.00 公分
寬度=  34.70 公分
高度=  89.10 公分
體積= 37101.24 立方公分
請輸入長度 寬度 高度 : (長度999 離開) 999 1 3
離開程式
長度= 999.00 公分
寬度=   1.00 公分
高度=   3.00 公分
體積= 2997.00 立方公分

>>> 
  

程式集訓 A001: HelloWorld

#coding=utf8


#程式集訓 A001: HelloWorld
'''
          A001: HelloWorld
'''
print( "Hello  Python World")



程式集訓 M90H007: 考試調分(低成60高100)

#coding=utf8

#程式集訓 M90H007: 考試調分(低成60高100)
'''
    ( max-min ) / ( max-原始成績 ) = ( 100-60 ) / ( 100-調整後的成績 )
'''

initial_value = 0
list_length = 20
sample_list1 = [initial_value]*list_length
sample_list2 = [initial_value]*list_length
i=0
print("請輸入20位學生的成績: ")
while i<=19:
  while True:
    try:
      print("第",i+1,"位" ,end="")             
      c1=int(input("學生的成績: "))
      if (c1>=0 and c1<=100):
          break
      else:
          print ('這是不合法的輸入.  請再輸入一次...')
          continue            
    except ValueError:
      print ('這是不合法的輸入.  請再輸入一次...')
      continue
   
  sample_list1[i]=int(c1)
  i=i+1
  

max1 = max(sample_list1)
min1 = min(sample_list1)
print("分數最高為",max1)
print("分數最低為",min1)          

for i in range (0,20):
   x=int(100-( (max1-sample_list1[i])*40/(max1-min1) ) + 0.5)
   sample_list2[i]=x


print("原始分數",sample_list1)
print("調整後分數",sample_list2) 

  


================= RESTART: D:/程式語言 Python 入門/程式集訓/M90H007.py =================
請輸入20位學生的成績: 
第 1 位學生的成績: 12
第 2 位學生的成績: 34
第 3 位學生的成績: 32
第 4 位學生的成績: 23
第 5 位學生的成績: 67
第 6 位學生的成績: 89
第 7 位學生的成績: 94
第 8 位學生的成績: 53
第 9 位學生的成績: 23
第 10 位學生的成績: 45
第 11 位學生的成績: 55
第 12 位學生的成績: 56
第 13 位學生的成績: 76
第 14 位學生的成績: 76
第 15 位學生的成績: 73
第 16 位學生的成績: 90
第 17 位學生的成績: 12
第 18 位學生的成績: 14
第 19 位學生的成績: 34
第 20 位學生的成績: 23
分數最高為 94
分數最低為 12
原始分數 [12, 34, 32, 23, 67, 89, 94, 53, 23, 45, 55, 56, 76, 76, 73, 90, 12, 14, 34, 23]
調整後分數 [60, 71, 70, 65, 87, 98, 100, 80, 65, 76, 81, 81, 91, 91, 90, 98, 60, 61, 71, 65]
>>> 

2016年9月15日 星期四

程式集訓 A016 : 三數排序

  

#coding=utf8

import math
#程式集訓 A016:三數排序
'''
           (A016) 三數排序 : 輸入三個正整數a、b、c,將a、b、c從小排到大。
'''
#==========================
def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass

    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass

    return False
#==========================
    
print("      輸入三個正整數a、b、c  ")
print("==================")
#==========================
n=1
while n!=0:
  a=input("輸入 A=")
  if (is_number(a) != True) :
     print ('這是不合法的輸入.  請再輸入一次...')
     n=1
  else:
     A=float(a)
     n=0
#==========================
n=1
while n!=0:
  a=input("輸入 B=")
  if (is_number(a) != True) :
     n=1
     print ('這是不合法的輸入.  請再輸入一次...')
  else:
     B=float(a)
     n=0
#==========================
n=1
while n!=0:
  a=input("輸入 C=")
  if (is_number(a) != True) :
     n=1
     print ('這是不合法的輸入.  請再輸入一次...')
  else:
     C=float(a)
     n=0

#==========================
# python 判斷後 只執行一次 故需判斷3次
if  (A>B):
     A,B=B,A
elif (A>C):
     A,C=C,A
elif (B>C):
    B,C=C,B
#==========================
if  (A>B):
     A,B=B,A
elif (A>C):
     A,C=C,A
elif (B>C):
    B,C=C,B
#==========================
if  (A>B):
     A,B=B,A
elif (A>C):
     A,C=C,A
elif (B>C):
    B,C=C,B
#==========================

print (A,"<<",B,"<<",C)


    輸入三個正整數a、b、c  
==================
輸入 A=12
輸入 B=4
輸入 C=45
4.0 << 12.0 << 45.0
>>> 

程式集訓 A016 : 三數排序

  

#coding=utf8

import math
#程式集訓 A016:三數排序
'''
           (A016) 三數排序 : 輸入三個正整數a、b、c,將a、b、c從小排到大。
'''
#==========================
def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass

    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass

    return False
#==========================
    
print("      輸入三個正整數a、b、c  ")
print("==================")
#==========================
n=1
while n!=0:
  a=input("輸入 A=")
  if (is_number(a) != True) :
     print ('這是不合法的輸入.  請再輸入一次...')
     n=1
  else:
     A=float(a)
     n=0
#==========================
n=1
while n!=0:
  a=input("輸入 B=")
  if (is_number(a) != True) :
     n=1
     print ('這是不合法的輸入.  請再輸入一次...')
  else:
     B=float(a)
     n=0
#==========================
n=1
while n!=0:
  a=input("輸入 C=")
  if (is_number(a) != True) :
     n=1
     print ('這是不合法的輸入.  請再輸入一次...')
  else:
     C=float(a)
     n=0

#==========================
# python 判斷後 只執行一次 故需判斷3次
if  (A>B):
     A,B=B,A
elif (A>C):
     A,C=C,A
elif (B>C):
    B,C=C,B
#==========================
if  (A>B):
     A,B=B,A
elif (A>C):
     A,C=C,A
elif (B>C):
    B,C=C,B
#==========================
if  (A>B):
     A,B=B,A
elif (A>C):
     A,C=C,A
elif (B>C):
    B,C=C,B
#==========================

print (A,"<<",B,"<<",C)


    輸入三個正整數a、b、c  
==================
輸入 A=12
輸入 B=4
輸入 C=45
4.0 << 12.0 << 45.0
>>> 

程式集訓 A016 : 三數排序

#coding=utf8

#程式集訓 A016:三數排序
'''
           (A016) 三數排序 : 輸入三個正整數a、b、c,將a、b、c從小排到大。
'''
list_length =3
initial_value = 0
sample_list1 = [initial_value]*list_length
sample_list2 = [initial_value]*list_length

#==========================
print("==============================")
while True:
  try:
    a1,a2,a3=(input("輸入三個正整數a、b、c 用空白隔開 ==> ")).split()
    break
  except ValueError:
    print ('這是不合法的輸入.  請再輸入一次...')
    continue
   
sample_list1[0]=int(a1)
sample_list1[1]=int(a2)
sample_list1[2]=int(a3)

sample_list2=sorted(sample_list1)
j=len(sample_list2)
for i in range(0,j):
     if i==(len(sample_list2)-1):
         print(sample_list2[i])
     else:
         print(sample_list2[i],'<',end='')

==============================
輸入三個正整數a、b、c 用空白隔開 ==> 12 4 45
4 <12 <45

>>> 


程式集訓 A016 : 三數排序

#coding=utf8

#程式集訓 A016:三數排序
'''
           (A016) 三數排序 : 輸入三個正整數a、b、c,將a、b、c從小排到大。
'''
list_length =3
initial_value = 0
sample_list1 = [initial_value]*list_length
sample_list2 = [initial_value]*list_length

#==========================
print("==============================")
while True:
  try:
    a1,a2,a3=(input("輸入三個正整數a、b、c 用空白隔開 ==> ")).split()
    break
  except ValueError:
    print ('這是不合法的輸入.  請再輸入一次...')
    continue
   
sample_list1[0]=int(a1)
sample_list1[1]=int(a2)
sample_list1[2]=int(a3)

sample_list2=sorted(sample_list1)
j=len(sample_list2)
for i in range(0,j):
     if i==(len(sample_list2)-1):
         print(sample_list2[i])
     else:
         print(sample_list2[i],'<',end='')

==============================
輸入三個正整數a、b、c 用空白隔開 ==> 12 4 45
4 <12 <45

>>> 


程式集訓 A006:輸入之正零負

(A006) 輸入之正零負 : 輸入一整數N,如果N大於0,則輸出"N>0",
       如果N等於0,則輸出"N=0",如果N小於0,則輸出"N<0"。 

#coding=utf8

from sys import exit
import math

#程式集訓 A006:輸入之正零負
'''
         (A006) 輸入之正零負 : 輸入一整數N,如果N大於0,則輸出"N>0",
         如果N等於0,則輸出"N=0",如果N小於0,則輸出"N<0"。 
'''
def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass

    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass

    return False

#==========================
do=1
print("輸入一整數N 判斷 大於 等於 小於 0 ")
print("輸入 n=999 離開程式")
while do!=0:
  n=1
  while n!=0:
    a=input("輸入 n= ")
    if (is_number(a) != True) :
       print ('這是不合法的輸入.  請再輸入一次...')
       n=1
    else:
       A=float(a)
       n=0
#==========================
  if (int(A)==999) :
     do=0
     print("結束程式")
     break
#==========================
  if (A>0 ):
      print("n > 0")
  elif (A==0 ):
     print("n = 0")
  else:

     print("n < 0")



輸入一整數N 判斷 大於 等於 小於 0 
輸入 n=999 離開程式
輸入 n= 12
n > 0
輸入 n= 34
n > 0
輸入 n= -99
n < 0
輸入 n= 0
n = 0
輸入 n= 999
結束程式
>>> 

程式集訓 A005:一元二次方根

(A005) 一元二次方根 : 從命令視窗輸入一元二次方程式(AX^2+BX+C=0)的三個係數,
       若該一元二次方程式有解,請印其兩個解,若無解則印"None"。請使用double做為係數
       及解的型態。解公式為 (-B+sqrt(D))/(2A) 和 (-B-sqrt(D))/(2A)
#coding=utf8

import math
#程式集訓 A005:一元二次方根
'''
         (A005) 一元二次方根 : 從命令視窗輸入一元二次方程式(AX^2+BX+C=0)的三個係數,
         若該一元二次方程式有解,請印其兩個解,若無解則印"None"。請使用double做為係數
         及解的型態。解公式為 (-B+sqrt(D))/(2A) 和 (-B-sqrt(D))/(2A)
'''
def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass

    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass

    return False

print("       (A005) 一元二次方根")
print("==================")
print("AX^2+BX+C=0: A B C?")

#==========================
n=1
while n!=0:
  a=input("輸入 A=")
  if (is_number(a) != True) :
     print ('這是不合法的輸入.  請再輸入一次...')
     n=1
  else:
     A=float(a)
     n=0
#==========================
n=1
while n!=0:
  a=input("輸入 B=")
  if (is_number(a) != True) :
     n=1
     print ('這是不合法的輸入.  請再輸入一次...')
  else:
     B=float(a)
     n=0
#==========================
n=1
while n!=0:
  a=input("輸入 C=")
  if (is_number(a) != True) :
     n=1
     print ('這是不合法的輸入.  請再輸入一次...')
  else:
     C=float(a)
     n=0

#==========================
if ( (B*B-4*A*C) >= 0 ) :
   x1 = ( -B + math.sqrt(B*B-4*A*C) ) / ( 2*A )
   x2 = ( -B  - math.sqrt(B*B-4*A*C) ) / ( 2*A )
   print("X1=",'{:6.2f}'.format(x1)," , X2=",'{:6.2f}'.format(x2))
else:

   print("無實根")



>>> 
================== RESTART: D:/程式語言 Python 入門/程式集訓/A005.py ==================
       (A005) 一元二次方根
==================
AX^2+BX+C=0: A B C?
輸入 A=1
輸入 B=-6
輸入 C=8
X1=   4.00  , X2=   2.00
>>> 
================== RESTART: D:/程式語言 Python 入門/程式集訓/A005.py ==================
       (A005) 一元二次方根
==================
AX^2+BX+C=0: A B C?
輸入 A=1
輸入 B=-5
輸入 C=-14
X1=   7.00  , X2=  -2.00
>>> 

程式集訓 A006:輸入之正零負

(A006) 輸入之正零負 : 輸入一整數N,如果N大於0,則輸出"N>0",
       如果N等於0,則輸出"N=0",如果N小於0,則輸出"N<0"。 

#coding=utf8

from sys import exit
import math

#程式集訓 A006:輸入之正零負
'''
         (A006) 輸入之正零負 : 輸入一整數N,如果N大於0,則輸出"N>0",
         如果N等於0,則輸出"N=0",如果N小於0,則輸出"N<0"。 
'''
def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass

    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass

    return False

#==========================
do=1
print("輸入一整數N 判斷 大於 等於 小於 0 ")
print("輸入 n=999 離開程式")
while do!=0:
  n=1
  while n!=0:
    a=input("輸入 n= ")
    if (is_number(a) != True) :
       print ('這是不合法的輸入.  請再輸入一次...')
       n=1
    else:
       A=float(a)
       n=0
#==========================
  if (int(A)==999) :
     do=0
     print("結束程式")
     break
#==========================
  if (A>0 ):
      print("n > 0")
  elif (A==0 ):
     print("n = 0")
  else:

     print("n < 0")



輸入一整數N 判斷 大於 等於 小於 0 
輸入 n=999 離開程式
輸入 n= 12
n > 0
輸入 n= 34
n > 0
輸入 n= -99
n < 0
輸入 n= 0
n = 0
輸入 n= 999
結束程式
>>> 

程式集訓 A005:一元二次方根

(A005) 一元二次方根 : 從命令視窗輸入一元二次方程式(AX^2+BX+C=0)的三個係數,
       若該一元二次方程式有解,請印其兩個解,若無解則印"None"。請使用double做為係數
       及解的型態。解公式為 (-B+sqrt(D))/(2A) 和 (-B-sqrt(D))/(2A)
#coding=utf8

import math
#程式集訓 A005:一元二次方根
'''
         (A005) 一元二次方根 : 從命令視窗輸入一元二次方程式(AX^2+BX+C=0)的三個係數,
         若該一元二次方程式有解,請印其兩個解,若無解則印"None"。請使用double做為係數
         及解的型態。解公式為 (-B+sqrt(D))/(2A) 和 (-B-sqrt(D))/(2A)
'''
def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass

    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass

    return False

print("       (A005) 一元二次方根")
print("==================")
print("AX^2+BX+C=0: A B C?")

#==========================
n=1
while n!=0:
  a=input("輸入 A=")
  if (is_number(a) != True) :
     print ('這是不合法的輸入.  請再輸入一次...')
     n=1
  else:
     A=float(a)
     n=0
#==========================
n=1
while n!=0:
  a=input("輸入 B=")
  if (is_number(a) != True) :
     n=1
     print ('這是不合法的輸入.  請再輸入一次...')
  else:
     B=float(a)
     n=0
#==========================
n=1
while n!=0:
  a=input("輸入 C=")
  if (is_number(a) != True) :
     n=1
     print ('這是不合法的輸入.  請再輸入一次...')
  else:
     C=float(a)
     n=0

#==========================
if ( (B*B-4*A*C) >= 0 ) :
   x1 = ( -B + math.sqrt(B*B-4*A*C) ) / ( 2*A )
   x2 = ( -B  - math.sqrt(B*B-4*A*C) ) / ( 2*A )
   print("X1=",'{:6.2f}'.format(x1)," , X2=",'{:6.2f}'.format(x2))
else:

   print("無實根")



>>> 
================== RESTART: D:/程式語言 Python 入門/程式集訓/A005.py ==================
       (A005) 一元二次方根
==================
AX^2+BX+C=0: A B C?
輸入 A=1
輸入 B=-6
輸入 C=8
X1=   4.00  , X2=   2.00
>>> 
================== RESTART: D:/程式語言 Python 入門/程式集訓/A005.py ==================
       (A005) 一元二次方根
==================
AX^2+BX+C=0: A B C?
輸入 A=1
輸入 B=-5
輸入 C=-14
X1=   7.00  , X2=  -2.00
>>> 

2016年9月14日 星期三

python 程式設計50題測試範例-40 大數加法 -42 大數乘法

40、大數加法,兩個100位數以內的數字相加,列印出結果。

42、大數乘法,兩個100位數以內的數字相乘,列印出結果。

大數問題
一、基本觀念
在某些情況下,我們必須處理位數相當多的一個整數,例如 100 位數,系統內建的資料型態不管是 intlong intlong long int 等,位數顯然都不夠用。要解決這個問題,我們必須自己用程式來處理,最簡單的方法,就是模仿人工處理數字的方式,也就是把數字拆成一個位數一個位數,這個時候我們可以用一個陣列來完成這個動作。不過,這樣一來,所有對於這種超大整數的處理,包括輸入一個大數、兩個大數相加、印出一個大數等等,都需要我們自己寫一個函數來處理。至於這個陣列要用什麼樣的資料型態,因為兩個一位數相乘也不過才 81,所以我們可以用 char 的陣列來記錄一個超長整數,如:
char n[300];
就可以記錄 300 位數的資料。前面提到大數的輸入及輸出,都需要我們自己寫函數來處理,我們分別把它們定名為 Input()  Print()
#include <stdio.h>
#include <string.h>
#define LEN 300
int Input(char n[])
{
}
void Print(char n[])
{
}
void main()
{
 char a[LEN];
 Input(a);
 Print(a);
}
上面第三行 #define LEN 300 的意思,即是定義一個常數叫做 LEN,而它的值是 300,下面用到 LEN 的地方,在執行的時候便會自動變成 300。這樣寫的好處是,如果我們有好個地方都用到 300 這個數字,但是後來發現不夠用了,要將它改成 1000,這個時候要一行一行改,還可能不小心漏掉,如果用 #define 定義一個常數,則只要改一個地方就行了。接下來我們看到 Input() 函數要做的步驟:
1.  把該陣列的每一格數字歸零。
2.  將使用者輸入的數字以字串方式存到另一個字串。
3.  計算該字串的長度。
4.  從該字串的尾端(即個位數)開始一個一個位數往左,將它轉換成數字後,存到陣列對應的格子中。
我們把上面提到的字串及超長整數的陣列做一個比較:
字串
s[0]
s[1]
s[2]
s[3]
s[4]
s[5]
s[6]
s[7]
s[8]
s[9]
'1'
'2'
'3'
'4'
'5'
'6'
0
×
×
×
陣列
n[0]
n[1]
n[2]
n[3]
n[4]
n[5]
n[6]
n[7]
n[8]
n[9]
6
5
4
3
2
1
0
0
0
0
上面提到的 Input() 的程式碼可以寫成:
int Input(char n[])
{
 char s[LEN];
 int i, l;
 for(i=0; i<LEN; i++)
   n[i]=0;
 if(scanf("%s", s)<1) return -1;
 l=strlen(s);
 for(i=0; i<l; i++)
   n[i]=s[l-i-1]-'0';
 return 0;
}
上面的 Input() 函數為了要得知是否有資料輸入,所以我們利用傳回值 0 代表輸入成功,傳回 -1 代表傳入失敗。至於 Print() 函數要做的步驟為:
1.  從該陣列最後面往回找到第一個不是 0 的數字。
2.  從該位數字往左邊依序把它們一個一個印出來。
3.  印出換行符號。
它的程式碼可以寫成:
void Print(char n[])
{
 int i;
 for(i=LEN-1; i>0; i--)
   if(n[i]!=0) break;
 for(; i>=0; i--)
   printf("%d", n[i]);
 printf("\n");
}
寫成之後,我們可以先輸入一個約 60 位數的數字,看是不是可以正常印出結果。

二、大數相加
接下來我們來寫一個處理兩個大數相加的題目,接著上一段的程式,我們接下來要寫一個處理相加的函數 Add(),它的做法就跟小學時的加法運算一樣,從個位數開始,一個位數一個位數相加,如果有超過 10 的部分,就把它往前進位。例如:
大數 A
0
1
2
3
4
5
6
7
8
9
大數 B
0
1
2
3
4
5
6
7
8
9
相加
0
2
4
6
8
10
12
14
16
18
進位
0
2
4
6
9
1
3
5
7
8
下面的程式碼可以參考看看:
void Add(char a[], char b[], char c[])
{
 int i;
 for(i=0; i<LEN; i++)
   c[i]=a[i]+b[i];
 for(i=0; i<LEN-1; i++) {
   if(c[i]>=10) {
     c[i+1]+=c[i]/10;
     c[i]=c[i]%10;
   }
 }
}
接下來把主程式 main() 改寫成:
void main()
{
 char a[LEN], b[LEN], c[LEN];
 Input(a);
 Input(b);
 Add(a, b, c);
 Print(c);
}

三、#10106 ─ Product
題目:按這裡
說明:每組測試資料有 2 列,分別代表 2 個大數 XY ( 0 <= XY < 10250),輸出 X*Y 的結果。
這一題的大數位數有 250 位,我們原先宣告的 LEN 300 所以已經夠用了。因為乘出來的積的最大位數為原來的兩倍,所以那一行 C[LEN] 要改成 C[LEN*2],而 Print() 函數裡面的 i=LEN-1 也要改成 i=LEN*2-1。接下來,我們要寫一個乘(Multiply)的函數 Mul(),它的做法就跟小學的乘法原理是一樣的,下面我們來看到它的程式碼:
void Mul(char a[], char b[], char c[])
{
 int i, j;
 for(i=0; i<LEN*2; i++)
   c[i]=0;
 for(i=0; i<LEN; i++) {
   for(j=0; j<LEN; j++) {
     c[i+j]+=a[j]*b[i];
     if(c[i+j]>=10) {
       c[i+j+1]+=c[i+j]/10;
       c[i+j]=c[i+j]%10;
     }
   }
 }
}
再把主程式改成:
void main()
{
 char a[LEN], b[LEN], c[LEN*2];
 Input(a);
 Input(b);
 Mul(a, b, c);
 Print(c);
}
最後再改成連續輸入的寫法:
void main()
{
 char a[LEN], b[LEN], c[LEN*2];
 while(1) {
   if(Input(a)) return;
   Input(b);
   Mul(a, b, c);
   Print(c);
 }
}

0
1
2
3
4
5
6
7
8
9
10
0
1
2
3
4
5
6
7
8
9
10
 
1
0
0
0
0
0
0
0
0
0
1
 
0
0
1
2
3
4
5
6
7
8
9
 
9
9
9
9
9
9
9
9
9
9
9
 
0
0
1
2
3
4
5
6
7
8
9
1
1
1
1
1
1
1
1
1
1
1
0
 
0
0
0
0
0
1
1
1
1
1
0
1
1
0
0
0
0
0
0
0
0
0
0
 
0
0
2
4
6
9
1
3
5
7
8
9
0
0
0
0
0
0
0
0
0
9
9
0
0
0
0
0
0
0
0
0
9
9
0
0
0
0
0
0
0
0
0
9
9
0
0
0
0
0
0
0
0
0
9
9
0
0
0
0
0
0
0
0
0
9
9
0
0
0
0
0
0
0
0
0
9
9
0
0
0
0
0
0
0
0
0
9
9
0
0
0
0
0
0
0
0
0
9
9
0
0
0
0
0
0
0
0
0
9
9
0
0
0
0
0
0
0
0
0
9
9
0
0
0
0
0
0
0
0
0
9
1
1
1
1
1
1
1
1
1
1
1
0
0
0
0
0
0
0
0
0
0
 
1
0
0
0
0
0
0
0
0
0
0
8
9
9
9
9
9
9
9
9
9
9
21
20
19
18
17
16
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
0
0
0
9
18
27
36
45
54
63
72
81
0
0
8
16
24
32
40
48
56
64
72
0
0
7
14
21
28
35
42
49
56
63
0
0
6
12
18
24
30
36
42
48
54
0
0
5
10
15
20
25
30
35
40
45
0
0
4
8
12
16
20
24
28
32
36
0
0
3
6
9
12
15
18
21
24
27
0
0
2
4
6
8
10
12
14
16
18
0
0
1
2
3
4
5
6
7
8
9
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
2
4
6
9
13
18
22
25
26
25
24
20
15
8
 
0
0
0
0
1
5
2
4
1
5
7
8
7
5
0
1
9
0
5
2
1




程式 :

#coding=utf8

initial_value = 'x'
list_length = 100
sample_list1 = [ initial_value for i in range(100)]   #0--99 
sample_list2 = [initial_value]*list_length

initial_value = 0
sample_list3 = [initial_value]*list_length
sample_list4 = [initial_value]*list_length
sample_list5 = [initial_value]*list_length

sample_list6 = [initial_value]*list_length*2    #乘法的積  Product =a * b 

print("40、大數加法,兩個100位數以內的數字相加,列印出結果。")
print("41、大數減法,兩個100位數以內的數字相減,列印出結果。")
print("42、大數乘法,兩個100位數以內的數字相乘,列印出結果。")
print("43、大數除法,兩個100位數以內的數字相除,列印出結果。")
print("===========================================")
print("輸入範例 0123456789=第一位數為0=1億2千3百4拾5萬6千7百8拾9==")
print("===========================================")

print("請輸入 被加數(被減數,被乘數,被除數) =第一位數為0===")

while True:
     b=int(input("請輸入數值 0 <  a  <9  ,a=10離開:"))
     try:
        b= int(b)
       
     except ValueError:
       print ('這是不合法的輸入.  請再輸入一次...')
       continue
        
     if ( b ==0 ):
       break

sample_list1[0]=0

a=1
k=1
while(a != 0):
  while True:
     b=int(input("請輸入數值 0 <  a  <9  ,a=10離開:"))
     try:
        b= int(b)
       
     except ValueError:
       print ('這是不合法的輸入.  請再輸入一次...')
       continue
        
     if ( b >=0 and b<=10):
       break
      
  if b==10:
     a=0
     break

  if (k>=100) :
     a=0
     break
    
  sample_list1[k]=b
  k=k+1


j=len(sample_list1)
for i in range(0,k):
     sample_list3[j-(k-i)]=sample_list1[i]

j=len(sample_list1)
for i in range(0,j):
     print(sample_list3[i],end="")
print()
     
print("===========================================")
print("請輸入 加數(減數,乘數,除數)=第一位數為0=========")    

while True:
     b=int(input("請輸入數值 0 <  a  <9  ,a=10離開:"))
     try:
        b= int(b)
       
     except ValueError:
       print ('這是不合法的輸入.  請再輸入一次...')
       continue
        
     if ( b ==0 ):
       break

sample_list2[0]=0

a=1
l=1
while(a != 0):
  while True:
     b=int(input("請輸入數值 0 <  a  <9  ,a=10離開:"))
     try:
        b= int(b)
       
     except ValueError:
       print ('這是不合法的輸入.  請再輸入一次...')
       continue
       
     if ( b >=0 and b<=10):
       break
      
  if b==10:
     a=0
     break

  if (l>=100) :
     a=0
     break
    
  sample_list2[l]=b
  l=l+1


j=len(sample_list1)
for i in range(0,l):
     sample_list4[j-(l-i)]=sample_list2[i]

j=len(sample_list1)
for i in range(0,j):
     print(sample_list4[i],end="")
print()

#================================

cy=0
j=len(sample_list1)-1

for i in range(j,-1,-1):
   sample_list5[i]= sample_list3[i]+sample_list4[i]+cy
   cy= sample_list5[i]//10
   sample_list5[i]=sample_list5[i]%10

print("===========================================")
print("相加結果==>",end="")

#判斷 被加數或加數的 長度 哪一個 長


if k>=l:
   m=k
else:
   m=l
   
j=len(sample_list1)-1
for i in range((j-m),j+1):     
     print(sample_list5[i],end="")

print()
#================================

cy=0
m=len(sample_list1)-1

for i in range(m,-1,-1):
  for j in range(m,-1,-1):
       sample_list6[i+j]=sample_list6[i+j]+sample_list3[j]*sample_list4[i]
       if sample_list6[i+j]>=10 :
           sample_list6[i+j-1]=sample_list6[i+j-1]+sample_list6[i+j]//10
           sample_list6[i+j]=sample_list6[i+j]%10

print("===========================================")
print("相乘的結果==>",end="")

if k>=l:
   m=2*k
else:
   m=2*l
j=len(sample_list6)-1
for i in range(j-m,j):     
     print(sample_list6[i],end="")

print()



結果:

================= RESTART: D:\程式語言 Python 入門\50題\Ex50-40.py =================
40、大數加法,兩個100位數以內的數字相加,列印出結果。
41、大數減法,兩個100位數以內的數字相減,列印出結果。
42、大數乘法,兩個100位數以內的數字相乘,列印出結果。
43、大數除法,兩個100位數以內的數字相除,列印出結果。
===========================================
輸入範例 0123456789=第一位數為0=1億2千3百4拾5萬6千7百8拾9==
===========================================
請輸入 被加數(被減數,被乘數,被除數) =第一位數為0===
請輸入數值 0 <  a  <9  ,a=10離開:0
請輸入數值 0 <  a  <9  ,a=10離開:1
請輸入數值 0 <  a  <9  ,a=10離開:2
請輸入數值 0 <  a  <9  ,a=10離開:3
請輸入數值 0 <  a  <9  ,a=10離開:4
請輸入數值 0 <  a  <9  ,a=10離開:5
請輸入數值 0 <  a  <9  ,a=10離開:6
請輸入數值 0 <  a  <9  ,a=10離開:7
請輸入數值 0 <  a  <9  ,a=10離開:8
請輸入數值 0 <  a  <9  ,a=10離開:9
請輸入數值 0 <  a  <9  ,a=10離開:10
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000123456789
===========================================
請輸入 加數(減數,乘數,除數)=第一位數為0=========
請輸入數值 0 <  a  <9  ,a=10離開:0
請輸入數值 0 <  a  <9  ,a=10離開:1
請輸入數值 0 <  a  <9  ,a=10離開:2
請輸入數值 0 <  a  <9  ,a=10離開:3
請輸入數值 0 <  a  <9  ,a=10離開:4
請輸入數值 0 <  a  <9  ,a=10離開:5
請輸入數值 0 <  a  <9  ,a=10離開:6
請輸入數值 0 <  a  <9  ,a=10離開:7
請輸入數值 0 <  a  <9  ,a=10離開:8
請輸入數值 0 <  a  <9  ,a=10離開:9
請輸入數值 0 <  a  <9  ,a=10離開:10
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000123456789
===========================================
相加結果==>00246913578
===========================================
相乘的結果==>00015241578750190521
>>>

MQTT Explorer 與 Node-Red 介面的實驗

 MQTT Explorer 與 Node-Red 介面的實驗 MQTT EXplorer 與 Node-Red介面的設定 (1) 設定  MQTT EXplorer Client    (2)        Node-Red LED ON  --> MQTT Explor...