Сократите дробь (функция)
Сократите дробь (n / m), то есть выведите два других числа p и q таких, что (n / m) = (p / q) и дробь (p / q) — несократимая.
Решение оформите в виде функции ReduceFraction(n, m), получающая значения n и m и возвращающей кортеж из двух чисел (return p, q)."
Задачу решила, код вроде работает, но проверку не проходит — требуется такой вывод:
Тест 1
Входные данные:
12
16
Вывод программы:
3 4
Но ведь при возврате двух значений автоматом создается кортеж, а я в силу недостатка знаний не понимаю, как сделать так, чтобы выводилось именно как в примере. Пробовала присваивать значения переменным, распаковывать кортеж — без толку. Помогите, пожалуйста, уже нет никаких идей, а задачу надо сдать, иначе курс не будет считаться пройденным.
Собственно мой код:
Даны два натуральных числа n и m. Сократите дробь (n / m), то есть выведите два других числа p и q таких, что (n / m) =
Даны два натуральных числа n и m. Сократите дробь (n / m), то есть выведите два других числа p и.
Функция преобразующая дробь к несократимому виду
В задаче нельзя использовать стандарт функции и дополнительные модули. Необходимо реализовать.
Сократите алгебраическую дробь
Сократите алгебраическую дробь:
Алгоритм Евклида — Сократите дробь
Дано натуральные числа a і b, которые обозначают числитель и знаменатель простой дроби. Сократите.
Сократите дробь вида x/y, используя метод определения НОД(a, b)
Методы. Вызов метода Решить задачу используя вызов метода. Сократите дробь вида x/y, используя.
Does Python have a function to reduce fractions?
For example, when I calculate 98/42 I want to get 7/3 , not 2.3333333 , is there a function for that using Python or Numpy ?
4 Answers 4
The fractions module can do that
There’s a recipe over here for a numpy gcd. Which you could then use to divide your fraction
![]()
Addition to John’s answer:
To get simplified fraction from a decimal number (say 2.0372856077554062)
Using Fraction gives the following output:
To get simplified answer :
![]()
Using the math gcd from the math module
![]()
Does Python have a function to reduce fractions?
No there is no built-in or external function, still you have two solutions.
1. Using fractions module
You can use Fraction objects from fractions module. From the documentation:
In this module a fraction is implicitly reduced, you can get the numerator and the denominator:
2. Reduction using the GCD
Any fraction can be reduced using the GCD, greatest common factor, of numerator and denominator: a/b == (a/gcd)/(b/gcd) .
GCD function is available both from numpy and math modules:
There is an alternative, but I do not consider it as valid for common needs: Use symbolic math with module sympy.
This allows to work with exact numbers at the cost of a loss of efficiency. sympy is it’s own world and some learning time is required.
fractions — Rational numbers¶
The fractions module provides support for rational number arithmetic.
A Fraction instance can be constructed from a pair of integers, from another rational number, or from a string.
class fractions. Fraction ( numerator = 0 , denominator = 1 ) ¶ class fractions. Fraction ( other_fraction ) class fractions. Fraction ( float ) class fractions. Fraction ( decimal ) class fractions. Fraction ( string )
The first version requires that numerator and denominator are instances of numbers.Rational and returns a new Fraction instance with value numerator/denominator . If denominator is 0 , it raises a ZeroDivisionError . The second version requires that other_fraction is an instance of numbers.Rational and returns a Fraction instance with the same value. The next two versions accept either a float or a decimal.Decimal instance, and return a Fraction instance with exactly the same value. Note that due to the usual issues with binary floating-point (see Floating Point Arithmetic: Issues and Limitations ), the argument to Fraction(1.1) is not exactly equal to 11/10, and so Fraction(1.1) does not return Fraction(11, 10) as one might expect. (But see the documentation for the limit_denominator() method below.) The last version of the constructor expects a string or unicode instance. The usual form for this instance is:
where the optional sign may be either ‘+’ or ‘-’ and numerator and denominator (if present) are strings of decimal digits (underscores may be used to delimit digits as with integral literals in code). In addition, any string that represents a finite value and is accepted by the float constructor is also accepted by the Fraction constructor. In either form the input string may also have leading and/or trailing whitespace. Here are some examples:
The Fraction class inherits from the abstract base class numbers.Rational , and implements all of the methods and operations from that class. Fraction instances are hashable , and should be treated as immutable. In addition, Fraction has the following properties and methods:
Changed in version 3.2: The Fraction constructor now accepts float and decimal.Decimal instances.
Changed in version 3.9: The math.gcd() function is now used to normalize the numerator and denominator. math.gcd() always return a int type. Previously, the GCD type depended on numerator and denominator.
Changed in version 3.11: Underscores are now permitted when creating a Fraction instance from a string, following PEP 515 rules.
Changed in version 3.11: Fraction implements __int__ now to satisfy typing.SupportsInt instance checks.
Numerator of the Fraction in lowest term.
Denominator of the Fraction in lowest term.
Return a tuple of two integers, whose ratio is equal to the Fraction and with a positive denominator.
New in version 3.8.
Alternative constructor which only accepts instances of float or numbers.Integral . Beware that Fraction.from_float(0.3) is not the same value as Fraction(3, 10) .
From Python 3.2 onwards, you can also construct a Fraction instance directly from a float .
Alternative constructor which only accepts instances of decimal.Decimal or numbers.Integral .
From Python 3.2 onwards, you can also construct a Fraction instance directly from a decimal.Decimal instance.
Finds and returns the closest Fraction to self that has denominator at most max_denominator. This method is useful for finding rational approximations to a given floating-point number:
or for recovering a rational number that’s represented as a float:
Returns the greatest int <= self . This method can also be accessed through the math.floor() function:
Returns the least int >= self . This method can also be accessed through the math.ceil() function.
__round__ ( ) ¶ __round__ ( ndigits )
The first version returns the nearest int to self , rounding half to even. The second version rounds self to the nearest multiple of Fraction(1, 10**ndigits) (logically, if ndigits is negative), again rounding half toward even. This method can also be accessed through the round() function.
Решение задачи на сократимые дроби с помощью Python
Сокращение дробей — это простой математический процесс, который заключается в уменьшении дроби до наименьших возможных пропорций, переставляя числитель и знаменатель. Таким образом, сократить дробь 6/8 до несократимой формы 3/4 можно, поделив числитель и знаменатель на их наибольший общий делитель (НОД), который в данном случае равен 2.
Python является мощным языком программирования, который может использоваться для решения самых различных задач, включая задачи по работе с дробями. В этой статье мы рассмотрим, как можно решить задачу на сокращение дробей с помощью Python.
Алгоритм решения задачи
- Найти НОД числителя и знаменателя дроби.
- Разделить числитель и знаменатель на найденный НОД.
- Полученную дробь представить в виде несократимой дроби.
Код на Python
В этом коде мы определяем две функции — gcd и simplifyFraction . Функция gcd используется для нахождения НОД числителя и знаменателя дроби. Функция simplifyFraction используется для сокращения дроби путем деления числителя и знаменателя на найденный НОД и приведения дроби к несократимой форме.
Пример использования
Допустим, мы хотим сократить дробь 24/36.
Таким образом, мы уменьшили дробь 24/36 до несократимой формы 2/3.
Вывод
Python — отличный инструмент для решения задач на сокращение дробей. Благодаря мощным математическим функциям Python и простоте синтаксиса, выполнение операций на сокращение дробей может быть легко и быстро выполнено с помощью этого языка программирования.