[英]Converting Mix Numbers to Decimals in Python
我正在嘗試編寫一個程序,將三 (3) 個測量值(例如 11 1/2"、12 3/8"、11 5/8")轉換為十進制格式,然后找到三 (3) 個測量值的平均值。我已經有代碼可以找到十進制格式的三 (3) 個測量值的平均值。但是,我似乎無法弄清楚如何首先將混合數測量值轉換為小數...
num = int(input('How many numbers?: '))
total_sum = 0
for n in range(num):
numbers = int(input('Enter number : '))
total_sum += numbers
avg = total_sum/num
print('Average of ', num, ' numbers is :', avg)
您可以為此使用正則表達式:
import re
def mixed_to_decimal(mixed):
match = re.fullmatch(r'(\d+)\s+(\d+)/(\d+)"?', mixed)
if match is None:
raise ValueError("Invalid mixed number.")
a, b, c = map(int, match.groups())
return a + b / c
mixed_to_decimal('11 1/2"') # 11.5
mixed_to_decimal('11 3') # ValueError
mixed_to_decimal('6 3/4') # 6.75
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.