Commit 98445a0e authored by Taddeus Kroes's avatar Taddeus Kroes

Added helper function to check if a node matches a fraction format.

parent 7b359faf
from ..node import ExpressionLeaf as L, OP_MUL, OP_DIV
def gcd(a, b):
"""
Return greatest common divisor using Euclid's Algorithm.
......@@ -20,3 +23,34 @@ def least_common_multiple(*args):
Return lcm of args.
"""
return reduce(lcm, args)
def is_fraction(node, nominator, denominator):
"""
Check if a node represents the fraction of a given nominator and
denominator.
>>> from ..node import ExpressionLeaf as L
>>> l1, l2, a = L('a'), L(1), L(2)
>>> is_fraction(a / l2, a, 2)
True
>>> is_fraction(l1 / l2 * a, a, 2)
True
>>> is_fraction(l2 / l1 * a, a, 2)
False
"""
if node.is_op(OP_DIV):
nom, denom = node
return nom == nominator and denom == denominator
if node.is_op(OP_MUL):
# 1 / denominator * nominator
# nominator * 1 / denominator
left, right = node
fraction = L(1) / denominator
return (left == nominator and right == fraction) \
or (right == nominator and left == fraction)
return False
import unittest
from src.rules.utils import least_common_multiple
from src.rules.utils import least_common_multiple, is_fraction
from tests.rulestestcase import tree
class TestRulesUtils(unittest.TestCase):
......@@ -9,3 +10,11 @@ class TestRulesUtils(unittest.TestCase):
self.assertEqual(least_common_multiple(5, 6), 30)
self.assertEqual(least_common_multiple(5, 6, 15), 30)
self.assertEqual(least_common_multiple(2, 4), 4)
def test_is_fraction(self):
l1, a = tree('1, a')
self.assertTrue(is_fraction(a / 2, a, 2))
self.assertTrue(is_fraction(l1 / 2 * a, a, 2))
self.assertTrue(is_fraction(a * (l1 / 2), a, 2))
self.assertFalse(is_fraction(l1 / 3 * a, a, 2))
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment