简体   繁体   中英

How do I find the midpoint of two numbers that are represented as a string and partial fraction eg. '1 1/2 - 2'?

l = ['1 1/2 - 2', '1 - 1 1/2', '1 1/4 - 2', '1 1/4 - 2', '1 - 11/2', '3 - 5', '1 1/4 - 2']

How do I find the midpoint for each of ranges in the list? For example the first one '1 1/2 - 2' should be 1.75

Let's break this into a few parts. For each of the items in the list, we'll have to break it into its integer and fractional component, and then we'll have to convert both to decimals.

Unfortunately, mixed number support in the fractions module was deprecated in Python 3, so we'll have to build our own.

from fractions import Fraction

def mixed_to_float(s):
    return sum(map(lambda i : float(Fraction(i)), s.split(' ')))

list = ['1 1/2 - 2', '1 - 1 1/2', '1 1/4 - 2', '1 1/4 - 2', '1 - 11/2', '3 - 5', '1 1/4 - 2']
for item in list:
    parts = map(lambda i : mixed_to_float(i), item.split(" - "))
    print (sum(parts)/2)

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