简体   繁体   中英

Converting Mix Numbers to Decimals in Python

I'm trying to write a program that converts three (3) measurements (eg 11 1/2", 12 3/8", 11 5/8") to decimal format then finds the average of the three (3) measurements. I already have code that finds the avg of three (3) measurements in decimal format. However, I can't seem to figure out how to first convert the mix number measurements into decimals...

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)

You can use regex for this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM