Hướng dẫn mixed number python

Good question. Here's one solution using Fraction function. Fraction is nice because it reduces fractions. You use floor divide (//) to strip out the whole number and then feed the remaining fraction to Fraction:

Nội dung chính

  • How do you show fractions in Python?
  • Can Python handle fractions?
  • How do you calculate mixed fractions?
  • How do you solve mixed fractions step by step?

From fractions import Fraction
num = int(input('Type numerator'))
dem = int(input('Type denominator'))
Print str(num // dem) + ' and ' + str(Fraction(num%dem,dem)) if num//dem != 0 else str(Fraction(num%dem,dem))

[Python 9.5] (https://docs.python.org/2/library/fractions.html#fractions.Fraction) Extended reading on Fraction. Because you feed it num and dem rather than a pure decimal, it is pretty fail-safe.

This also gets rid of response of '0 and ...' which was bothering me.

Without using fractions module, we have to find the greatest common divider (borrowing gcd function from fractions) reduce our initial fraction and then use brilliant solution from @Jenner Felton

def gcdm(num,dem):
  while dem:
    num, dem = dem, num%dem
  return num
gcd = gcdm(num,dem)
num, dem = num/gcd, dem/gcd
Print "%d and %d/%d" % ((num//dem), (num%dem),dem) if num//dem !=0 else "%d/%d" % (num%dem,dem)


class Mixed2Improper:

    
    def __init__(self, fraction):
        self.whole_number = fraction['whole_number']
        self.numerator    = fraction['numerator']
        self.denominator  = fraction['denominator']

                  

def doConvert(self):

                 return self.whole_number * self.denominator + self.numerator


from MixedToImproper import Mixed2Improper

    fraction = {'whole_number':3, 'numerator':1, 'denominator':3}

print("    Converting from Mixed to Improper the fraction:\n")

print(   '{:55d}'.format(fraction['numerator']))
print('{:53d} {}'.format(fraction['whole_number'], '-'))
print(   '{:55d}'.format(fraction['denominator']))


mix2imp = Mixed2Improper(fraction)
fraction['numerator'] = mix2imp.doConvert()

print("\n")

print('{:52d}'.format(fraction['numerator']))
print('{:>52}'.format('Answer =      -'))
print('{:52d}'.format(fraction['denominator']))

print("\n\n")

Welcome to the Mixed Number Fractions wiki.

Easily input, display, and convert mixed number fractions in Python.

Currently supported Python versions: 3.x

About
The Mixed Number Fraction (Mixed) class is based on the standard library Fraction class. It was designed to be able to do anything and everything that a standard Fraction does, and a bit more. The Mixed constructor creates a Rational, as it inherits from Fraction which, in turn, inherits from numbers.Rational.

Usage

class mixed_fractions.Mixed(whole_number=0, numerator=0, denominator=1)
class mixed_fractions.Mixed(numerator=0, denominator=1)
class mixed_fractions.Mixed(other_mixed)
class mixed_fractions.Mixed(other_fraction))
class mixed_fractions.Mixed(float)
class mixed_fractions.Mixed(decimal)
class mixed_fractions.Mixed(string)

The first version requires that whole_number, numerator, and denominator are instances of numbers.Rational and returns a new Mixed instance with value whole_number + numerator/denominator. If denominator is 0, it raises a ZeroDivisionError. The second version requires that numerator and denominator are instances of numbers.Rational and returns a new Mixed instance with value numerator/denominator, exactly as standard Fraction does, and will also raise a ZeroDivisionError if denominator is 0. The third and fourth versions requires that other_mixed( or other_fraction) is an instance of numbers.Rational and returns a Mixed instance with the same value. The next two versions accept either a float or a decimal.Decimal instance, and return a Mixed instance with exactly the same value. Note that due to the usual issues with binary floating-point, the argument to Mixed(1.1) is not exactly equal to 1 1/10 (11/10), and so Mixed(1.1) does not return Mixed(1,1,10) as one might expect. The last version of the constructor expects a string or unicode instance. Unsupported types being passed to a Mixed constructor will raise a TypeError. The form for the string instance may be any of the following:

[sign] whole_number numerator '/' denominator

or

[sign] numerator '/' denominator

or

where the optional sign may be either ‘+’ or ‘-‘ and whole_number, numerator, and denominator (if present) are strings of decimal digits. In addition, any string that represents a finite value and is accepted by the float constructor is also accepted by the Mixed constructor. The string representation of denominator, if 0, will raise a ZeroDivisionError. An otherwise invalid string will raise a ValueError. In any form, the input string may also have leading and/or trailing whitespace. Here are some examples:

>>> from mixed_fractions import Mixed
>>> Mixed(16,-10)
Mixed(-1, 3, 5)
>>> Mixed(6,7,8)
Mixed(6, 7, 8)
>>> Mixed(123)
Mixed(123, 0, 1)
>>> Mixed()
Mixed(0, 0, 1)
>>> Mixed('3/7')
Mixed(0, 3, 7)
>>> Mixed('-3/7')
Mixed(0, -3, 7)
>>> Mixed('1.414213 \t\n')
Mixed(1, 414213, 1000000)
>>> Mixed('-.125')
Mixed(0, -1, 8)
>>> Mixed('7e-6')
Mixed(0, 7, 1000000)
>>> Mixed(2.25)
Mixed(2, 1, 4)
>>> Mixed(1.1)
Mixed(1, 225179981368525, 2251799813685248)
>>> from decimal import Decimal
>>> Mixed(Decimal('1.1'))
Mixed(1, 1, 10)

The Mixed class inherits from the fractions.Fraction class which inherits from the abstract base class numbers.Rational. Mixed implements all of the methods and operations from those classes. Mixed instances are hashable, and should be treated as immutable. In addition, Mixed has the following properties and methods:

fnumerator
Fractional portion numerator in lowest term. e.g. Mixed(3,4,5).fnumerator will yield 4.

whole
Mixed % 1 e.g. Mixed(3,4,5).whole will yield 3.

to_fraction()
Converts Mixed to Fraction. e.g. Mixed(3,4,5).to_fraction() will yield Fraction(19,5)

How do you show fractions in Python?

You have two options:.

Use float.as_integer_ratio() : >>> (0.25).as_integer_ratio() (1, 4) (as of Python 3.6, you can do the same with a decimal. Decimal() object.).

Use the fractions.Fraction() type: >>> from fractions import Fraction >>> Fraction(0.25) Fraction(1, 4).

Can Python handle fractions?

In Python the Fraction module supports rational number arithmetic. Using this module, we can create fractions from integers, floats, decimal and from some other numeric values and strings. There is a concept of Fraction Instance. It is formed by a pair of integers as numerator and denominator.

How do you calculate mixed fractions?

Step 1: Multiply the denominator with the whole number. Step 2: Add the numerator to the product obtained from step 1. Step 3: Write the mixed fraction with the sum obtained from step 2 as the numerator and the denominator of the original fractional part of the mixed fraction.

How do you solve mixed fractions step by step?

Step 1: Find the Lowest Common Multiple (LCM) between the denominators. Step 2: Multiply the numerator and denominator of each fraction by a number so that they have the LCM as their new denominator. Step 3: Add or subtract the numerators and keep the denominator the same.