Python練習【3】【羅馬數字轉換/查
- 2020 年 1 月 6 日
- 筆記
題目1:羅馬數字轉換 羅馬數字包含以下七種字元: I, V, X, L,C,D 和 M 字元 數值 I 1 V 5 X 10 L 50 C 100 D 500 M 1000
- 例如,羅馬數字2寫做 II,即為兩個並排放置的的 1,12寫做XII,即為 X + II ,27寫做XXVII,即為XX+V+II
- 在羅馬數字中,小的數字在大的數字的右邊。但 4 不寫作 IIII,而是 IV。數字 1 在數字 5 的左邊,所表示的數等於大數減小數得到的數值 4 。同樣地,數字 9 表示為 IX。這個規則只適用於以下六種情況: I 可以放在 V (5) 和 X (10) 的左邊,來表示 4 和 9 X 可以放在 L (50) 和 C (100) 的左邊,來表示 40 和 90 C 可以放在 D (500) 和 M (1000) 的左邊,來表示 400 和 900 給定一個羅馬數字,將其轉換成整數。輸入確保在 1 到 3999 範圍內
- 示例:
示例 1: 輸入: 「III」 輸出: 3 示例 2: 輸入: 「IV」 輸出: 4 示例 3: 輸入: 「IX」 輸出: 9 示例 4: 輸入: 「LVIII」 輸出: 58 解釋: C = 100, L = 50, XXX = 30 and III = 3. 示例 5: 輸入: 「MCMXCIV」 輸出: 1994 解釋: M = 1000, CM = 900, XC = 90 and IV = 4.
編程思路: 羅馬數字一般來說小數在大數後面,各數字譯成對應十進位相加即可 若小數在大數前面,則取對應的小數的相反數相加即可 例: IV=-1+5=4 CM=-100+1000=900: MCMXCIV=1000-100+1000-10+100-1+5=1994
程式碼: 羅馬數字轉十進位數函數: def roman_into_decimal(roman_num): ##羅馬數字轉十進位數函數 for i in roman_num: if i not in roman: print('請輸入正確的羅馬數字') return ## 遍歷輸入字元串,判斷是否為正確的羅馬數字,不是則提示並返回None num = 0 reduce = [roman_num[i] for i in range(len(roman_num) – 1) if roman[roman_num[i]] < roman[roman_num[i + 1]]] ## 判斷逆序的組合,並將逆序的首字母存入列表reduce for i in roman_num: num += (-roman[reduce.pop(reduce.index(i))]) if i in reduce else roman[i] ## 遍歷輸入的字元串,如果reduce中包含對應key值,則從reduce中彈出(去重)並減去對應value值 if 1<=num<=3999: print('對應十進位數:', num) ## 輸出對應10進位數 else: print('超出範圍,請輸入轉換值在1-3999之間的數')
主程式:
roman = dict(I=1, V=5, X=10, L=50, C=100, D=500, M=1000) ## 定義基本羅馬數字 while True: roman_in = input('請輸入轉換值在1-3999之間的羅馬數字:') roman_into_decimal(roman_in) ##調用函數
測試結果:


題目2:公共前綴 編寫一個函數來查找字元串數組中的最長公共前綴 如果不存在最長公共前綴,返回空字元串 ''
- 說明:所有輸入只包含小寫字母 a-z
示例 1: 輸入: [「flower」,」flow」,」flight」] 輸出: 「fl」 示例 2: 輸入: [「dog」,」racecar」,」car」] 輸出: 「」 解釋: 輸入不存在最長公共前綴
程式碼: 尋找公共前綴函數: def find_public_pro(string): ##尋找公共前綴函數 public_pro='' ##定義空字元串用於接收公共字元 for i in range(min([len(i) for i in string])): ##循環次數最長為最短字元串長度 for j in range(len(string)-1): if string[j][i]!=string[j+1][i]: return public_pro ##從首字母開始所有字元串同一位置出現字元不相等時返回public_pro else: public_pro=public_pro+string[0][i] ##從首字母開始所有字元串同一位置字元相等時,將該字元放入public_pro else: return public_pro ##for循環完畢說明最短字元串即為公共前綴,返回公共前綴
主程式:
while True: ##死循環 try: string_in=input('請輸入字元串數組(僅包含小寫字母):n例:["flower","flow","flight"]').replace('"','').strip('[').strip(']').replace(',',' ') ##以規定格式輸入時,去除字元串中無用的[]",等字元 if not string_in.replace(' ','').islower(): print('請輸入正確的字元串數組(僅包含小寫字母)') continue ##如果字元串不是純小寫字母,提示並刷新 string_in=string_in.split(' ') ##以空格分隔字元串為列表 print(find_public_pro(string_in)) except Exception as e: print('程式異常') ##程式異常提示,捕獲程式退出相關以外的所有異常 finally: if bool(input('按下Enter鍵繼續')): pass ##無論是否異常,都通過鍵盤暫停,防止頁面刷新以便觀察結果
測試結果:



python3中默認漢字屬於字母類,但其中壹/一等字屬於數字