Exemplo n.º 1
0
 def test_values(self):
     # Test multiply for numbers
     self.assertEqual(multiply(5, 3), 15)
     self.assertEqual(multiply(0, 0), 0)
     self.assertEqual(multiply(-5, 3), -15)
     self.assertEqual(multiply(.2, 1.7), .34)
     self.assertEqual(multiply(-7.2, -1.7), 12.24)
Exemplo n.º 2
0
def Calculator():
    print("************MAIN MENU**************")
    print()

    choice = int(
        input("""
                      1: Addition
                      2: Subtraction
                      3: Division
                      4: Multiplication
                      5: Remainder
                      6: Quit/log out
                      
                      Please enter your choice: """))
    if choice == 1:
        add()
    elif choice == 2:
        subtract()
    elif choice == 3:
        divide()
    elif choice == 4:
        multiply()
    elif choice == 5:
        modulus()
    elif choice == 6:
        sys.exit
    else:
        print("You must only select either 1,2,3,4,5, or 6.")
        print("Please try again")
        Calculator()
Exemplo n.º 3
0
def test_multiply():
	"""
	Tests that the multiply function works
	"""
	assert mp.multiply(5,5) == 25
	assert mp.multiply(3,0) == 0
	assert mp.multiply(10,1) == 10
Exemplo n.º 4
0
def test_multiply():
    """
	Tests that the multiply function works
	"""
    assert mp.multiply(5, 5) == 25
    assert mp.multiply(3, 0) == 0
    assert mp.multiply(10, 1) == 10
Exemplo n.º 5
0
def test_multiply_two_negative():
    assert_equals(multiply(BigInteger("-5"), BigInteger("-3")).digits, [1,5])
    result = multiply(BigInteger("-2"), BigInteger("3"))
    assert_equals(result.digits, [6])
    assert result.negative
    result = multiply(BigInteger("2"), BigInteger("-1"))
    assert_equals(result.digits, [2])
    assert result.negative
Exemplo n.º 6
0
 def test_rand(self):
     from inspect import isfunction
     from random import randint
     print("Should return 10 multiplications correctly")
     for _ in range(10):
         x, y = randint(0,100), randint(1,200)
         self.assertEqual( multiply( x, y ), x * y,"that's not the multiplication!")
Exemplo n.º 7
0
def sharpen(pic='lena.bmp', sharpen_times=2, img=None):
    im = None
    if img != None:
        im = img
    else:
        im = Image.open(pic)
    pixels = im.load()
    h, w = im.size
    r, g, b = seg_rgb(pixels, h, w)

    multiply_image = multiply.multiply(pic, sharpen_times)
    multiply_pixels = multiply_image.load()
    mh, mw = multiply_image.size
    mr, mg, mb = seg_rgb(multiply_pixels, mh, mw)

    linear_blur_image = linear_blur.linear_blur(pic)
    linear_blur_pixels = linear_blur_image.load()
    lbh, lbw = linear_blur_image.size
    lbr, lbg, lbb = seg_rgb(linear_blur_pixels, lbh, lbw)

    sr = find_sharpen(r, mr, lbr)
    sg = find_sharpen(g, mg, lbg)
    sb = find_sharpen(b, mb, lbb)

    sharpen_image = Image.new('RGB', (mh, mw), "black")
    si = sharpen_image.load()
    for i in xrange(mh):
        for j in xrange(mw):
            si[i, j] = (sr[i][j], sg[i][j], sb[i][j])
    sharpen_image.show()
    return sharpen_image
Exemplo n.º 8
0
def exponent(m, n):
    # base case
    if n == 1:
        return m
    # moving toward base case using recursion
    #return m*exponent(m,n-1)
    return multiply(m, exponent(m, n - 1))
def runMultiply():

    result = 0
    results = {}

    try:
        x = int(request.args.get('x'))
        y = int(request.args.get('y'))
    except:
        results = {
            "x": 0,
            "y": 0,
            "answer": 0,
            "error": True,
            "errorMessage": "Please give both x and y values"
        }
        resultsJSON = json.dumps(results)
        res = Response(response=resultsJSON,
                       status=400,
                       mimetype="application/json")
    else:
        result = multiply.multiply(x, y)
        results = {"x": x, "y": y, "answer": result, "error": False}
        resultsJSON = json.dumps(results)
        res = Response(response=resultsJSON,
                       status=200,
                       mimetype="application/json")

    res.headers["Content-Type"] = "application/json"
    res.headers["Access-Control-Allow-Origin"] = "*"

    return res
Exemplo n.º 10
0
def dispatch(s):
    resolve = s.split()
    operation = resolve[1]
    try:
        resolve[0] = int(resolve[0])
        resolve[2] = int(resolve[2])
    except:
        pass

    if operation == "+":
        return add.add(resolve[0], resolve[2])
    elif operation == "-":
        return minus.minus(resolve[0], resolve[2])
    elif operation == "*":
        return multiply.multiply(resolve[0], resolve[2])
    elif operation == "/":
        return divide.divide(resolve[0], resolve[2])
    elif operation == "!":
        return factorial.factorial(resolve[0])
    elif operation == "to_hex":
        return dec_to_hex.dec_to_hex(resolve[0])
    elif operation == "to_bin":
        pass
    elif operation == "inv":
        return inverse.inverse(resolve[0])
    elif operation == "**":
        return power.power(resolve[0], resolve[2])
Exemplo n.º 11
0
def test_four_multiply_carson():
    """Function that checks TypeError is raised when input is
    two strings."""
    from multiply import multiply
    try:
        assert multiply('string', 'string') == TypeError
    except TypeError:
        print('Cannot multiply string values.')
Exemplo n.º 12
0
 def test(self):
     self.assertEqual(multiply(1, 1), 1)
     self.assertEqual(multiply(2, 1), 2)
     self.assertEqual(multiply(2, 2), 4)
     self.assertEqual(multiply(3, 5), 15)
     self.assertEqual(multiply(1.5, 2.5), 3.75)
     self.assertEqual(multiply(0, 5), 0)
     self.assertEqual(multiply(0, 0), 0)
def test_multiply(setup_name):
    shares_of_messages_for_multiply, _, _ = create_shares_for_messages(
        setup_name, np.random.randint(0, prime - 1),
        np.random.randint(0, prime - 1))
    print("\nCalling multiply('{}', {})".format(
        setup_name, shares_of_messages_for_multiply))
    shares = multiply(setup_name,
                      shares_of_messages_for_multiply,
                      print_statements=print_statements)
    print("Multiply successful. Computed messages: {}".format(shares))
Exemplo n.º 14
0
def main():
    print("\n\nWelcome to My Math!\n")
    a = int(input("Enter your first whole number: "))
    b = int(input("Enter your second whole number: "))
    print("\n{} + {} = {}".format(a, b, add(a, b)))
    print("\n{} - {} = {}".format(a, b, subtract(a, b)))
    print("\n{} * {} = {}".format(a, b, multiply(a, b)))
    print("\n{} / {} = {}".format(a, b, divide(a, b)))
    print("\n{} % {} = {}".format(a, b, remainder(a, b)))
    print("\n{} ^ {} = {}".format(a, b, exponent(a, b)))
Exemplo n.º 15
0
 def test_001_t (self):
 	src_data = (0, 1, -2, 5.5, -0.5)
 	expected_result = (0, 2, -4, 11, -1)
 	src = blocks.vector_source_f (src_data)
 	mult = multiply(2)
 	snk = blocks.vector_sink_f ()
 	self.tb.connect (src, mult)
 	self.tb.connect (mult, snk)
 	self.tb.run ()
 	result_data = snk.data ()
 	self.assertFloatTuplesAlmostEqual (expected_result, result_data, 6)
Exemplo n.º 16
0
def int_power(a, b):
    # Raises a to the power b, where b needs to be an int
    int_or_float_check(a)
    int_check(b)
    res = 1
    for i in range(b):
        res = multiply(res, a)
    if res == 0 and a > 0:
        return sys.float_info.min
    else:
        return res
Exemplo n.º 17
0
def int_root(a, n):
    # Return n-th root of a, where b needs to be an int
    int_or_float_check(a)
    int_check(n)
    if n == 0:
        raise SyntaxError("Cannot calculate zero-th root")
    if a < 0 and modulo(n, 2) == 0:
        raise SyntaxError("Cannot do even root of negative number")
    epsilon = .00001
    x_0 = divide(a, n)
    x_1 = multiply(
        divide(1, n),
        add(multiply(add(n, -1), x_0), divide(a, int_power(x_0, add(n, -1)))))
    while abs(add(x_0, -x_1)) > epsilon:
        x_0 = x_1
        x_1 = multiply(
            divide(1, n),
            add(multiply(add(n, -1), x_0), divide(a,
                                                  int_power(x_0, add(n, -1)))))
    return x_1
Exemplo n.º 18
0
    def tick(self):
        self.led_matrix_painter.show_Text(self.get_date_string())
        back = Field(10, 20)

        self.currentrainbowstart += 1
        self.currentrainbowstart %= self.COLORS
        for x in range(10):
            for y in range(20):
                back.set_pixel(x, y, self.r[y + self.currentrainbowstart])
        self.draw_clock([255, 255, 255])
        rainbowtime = multiply(back, self.field_leds)
        self.rgb_field_painter.draw(rainbowtime)
        sleep(0.05)
Exemplo n.º 19
0
def isOrthogonal(matrix):
    if squareErr(matrix):
        print("The matrix is not orthogonal.")
        return False

    matrixT = transpose(matrix)

    if isIdentity(multiply(matrix, matrixT)):
        print("The matrix is orthogonal.")
        return True
    else:
        print("The matrix is not orthogonal.")
        return False
Exemplo n.º 20
0
def power(base, exponent, cache=None):
    """Returns base to the power of exponent.

    If exponent is less than 0, returns a BigInteger of 0.

    Neither BigInteger is modified during this operation.

    Args:
        base: BigInteger, the number to be multiplied.

        exponent: BigInteger, the exponent to apply to the base.

    Returns:
        A new BigInteger of the result of base**exponent.
    """
    if cache is None:
        cache = {}
    # Any negative exponent will be a fraction 0 < x < 1, so round down to 0
    if exponent < BigInteger("0"):
        return BigInteger("0")
    if exponent == BigInteger("0"):
        return BigInteger("1")
    if exponent == BigInteger("1"):
        return base
    print "Printing"
    print exponent.__hash__()
    if exponent in cache:
        print "Accessing cache: ", exponent
        return cache[exponent]
    half_exponent = divide(exponent, BigInteger("2"))
    half_result = power(base, half_exponent, cache)
    # a**n = a**(n/2) * 2 if n is even
    result = multiply(half_result, half_result)
    # Divide doesn't support mod or remainder, so check for an odd number
    # If exponent is odd, multiply by base one more time
    if exponent.digits[-1] in (1, 3, 5, 7, 9):
        result = multiply(result, base)
    cache[exponent] = result
    return result
Exemplo n.º 21
0
    def draw_clock(self, color: list = None):
        hour, minute, second = self.get_time()
        self.draw_digit(hour, 1, [255, 255, 255])
        self.draw_digit(minute, 4, [255, 255, 255])
        self.draw_digit(second, 7, [255, 255, 255])
        back = Field(10, 20)

        self.currentrainbowstart += 1
        self.currentrainbowstart %= self.COLORS
        for x in range(10):
            for y in range(20):
                back.set_pixel(x, y, self.r[y + self.currentrainbowstart])
        rainbowtime = multiply(back, self.field_leds)
        self.field_leds.field = rainbowtime.field
Exemplo n.º 22
0
 def test_matrix_multiplication(self):
     """Test the multiplication of matrices"""
     m1 = [
             [1, 2, 3],
             [2, 4, 6]
     ]
     m2 = [
             [1, 2],
             [2, 4],
             [3, 6]
     ]
     correct_answer = [
             [14, 28],
             [28, 56]
     ]
     result = multiply.multiply(m1, m2)
     self.assertEqual(result, correct_answer)
Exemplo n.º 23
0
def test_matrix_multiply():
    matrix1 = [[1, 2], [4.2, 5], [7, 8]]
    matrix2 = [[2.1, 1.1], [4.1, -1.1]]

    result = multiply(matrix1, matrix2)

    assert len(result) == 3
    assert len(result[0]) == 2

    assert result[0][0] == approx(10.3, rel=1e-5)
    assert result[0][1] == approx(-1.1, rel=1e-5)

    assert result[1][0] == approx(29.32, rel=1e-5)
    assert result[1][1] == approx(-0.88, rel=1e-5)

    assert result[2][0] == approx(47.5, rel=1e-5)
    assert result[2][1] == approx(-1.1, rel=1e-5)
Exemplo n.º 24
0
def test_matrix_multiply_1000x1000_benchmark():
    size = 1000
    rows1 = size
    columns1 = size
    columns2 = size

    matrix1 = [[random.uniform(-1, 1) for _ in range(columns1)]
               for _ in range(rows1)]
    matrix2 = [[random.uniform(-1, 1) for _ in range(columns2)]
               for _ in range(columns1)]

    start = timer()

    result = multiply(matrix1, matrix2)

    end = timer()

    print(
        f"\nMultiply {size}x{size} matrices with three loops: {end - start} s\n"
    )
    assert result[0][0] != 42
Exemplo n.º 25
0
def get_fraction(a):
    # Turns float into fraction
    int_or_float_check(a)
    if isinstance(a, int):
        return a, 1
    else:
        is_negative = False
        if a < 0:
            is_negative = True
            a = abs(a)
        fraction = str(a).split(".")
        original_denominator = 1
        for i in range(len(fraction[1])):
            original_denominator = multiply(original_denominator, 10)
        original_numerator = int(fraction[0] +
                                 fraction[1])  # Not addition but string concat
        common_denominator = GCD(original_numerator, original_denominator)
        numerator = int(divide(original_numerator, common_denominator))
        denominator = int(divide(original_denominator, common_denominator))
    if is_negative:
        numerator = -numerator
    return numerator, denominator
Exemplo n.º 26
0
from multiply import multiply
"""
_.multiply(6, 4);
// => 24
"""

print("multiply(6, 4) = {}".format(multiply(6, 4)))
Exemplo n.º 27
0
def test_numbers_3_4():
	assert multiply(3, 4) == 12
Exemplo n.º 28
0
def test_multiply_one_large():
    # 2**64 is just beyond the bounds of int, so Python makes it a long
    a = BigInteger("18446744073709551616")
    expect = [1, 8, 4, 4, 6, 7, 4, 4, 0, 7, 3, 7, 0, 9, 5, 5, 1, 6, 1, 6, 0, 0]
    assert_equals(multiply(a, BigInteger("100")).digits, expect)
Exemplo n.º 29
0
	def test_one_each(self):
		self.assertEqual(multiply.multiply(-5.5, 2), -11.0)
Exemplo n.º 30
0
	def test_two_pos(self):
		self.assertEqual(multiply.multiply(3, 6), 18)
Exemplo n.º 31
0
def test_string_a_3():
	assert multiply('a', 3) == 'aaa'
Exemplo n.º 32
0
	def test_two_neg(self):
		self.assertEqual(multiply.multiply(-1, -6), 6)
Exemplo n.º 33
0
def test_multiply_different_lengths():
    a = BigInteger("1012")
    b = BigInteger("35")
    assert_equals(multiply(a, b).digits, [3, 5, 4, 2, 0])
Exemplo n.º 34
0
def test_multiply_two_large():
    a = BigInteger("48446744073709551616")
    b = BigInteger("130808823666624465123")
    expected = BigInteger("6337261602759956545834207900472160288768")
    assert_equals(multiply(a, b), expected)
Exemplo n.º 35
0
def test_multiply(a, b, answer):
    """Test for multiply function."""
    from multiply import multiply
    assert multiply(a, b) == answer
Exemplo n.º 36
0
def test1():
    """checks that 3 * 4 is 12"""
    from multiply import multiply
    assert multiply(3, 4) == 12
Exemplo n.º 37
0
def test_multiply_carry():
    a = BigInteger("12")
    b = BigInteger("56")
    expected = BigInteger("672")
    assert_equals(multiply(a, b), expected)
Exemplo n.º 38
0
def test_multiply_small_numbers():
    a = BigInteger("2")
    b = BigInteger("3")
    assert_equals(multiply(a, b).digits, [6])
Exemplo n.º 39
0
#!/usr/bin/env python

"""
simple test of the multiply.pyx and c_multiply.c test code
"""


import numpy as np

import multiply

a = np.arange(12, dtype=np.float64).reshape((3,4))

print a

multiply.multiply(a, 3)

print a
Exemplo n.º 40
0
def test2():
    """checks that we can also multiply by non-integers"""
    from multiply import multiply
    assert multiply(2, 5.5) == 11
Exemplo n.º 41
0
def test3():
    """checks that we can also multiply by negatives"""
    from multiply import multiply
    assert multiply(-2, 5.5) == -11
Exemplo n.º 42
0
         break
     except ValueError:
         print("Необходимо ввести ЧИСЛО!")
         print("")
 print("")
 while True:
     sign = input(
         '''Нажмите кнопку, которая соответствует требуемому действию:
     1) +
     2) -
     3) *
     4) /
     :''')
     if sign in ['+', '-', '*', '/', '1', '2', '3', '4']:
         break
     else:
         print("Введите знак или цифру соответствующую знаку!")
         continue
 print("")
 if sign == '+' or sign == '1':
     from add import add
     add(value1, value2)
 elif sign == '-' or sign == '2':
     from subtraction import subtraction
     subtraction(value1, value2)
 elif sign == '*' or sign == '3':
     from multiply import multiply
     multiply(value1, value2)
 elif sign == '/' or sign == '4':
     from divide import divide
     divide(value1, value2)
Exemplo n.º 43
0
def test_multiply_zeroes():
    a = BigInteger("0")
    assert_equals(multiply(a, BigInteger("10")).digits, [0])
    assert_equals(multiply(a, a).digits, [0])
    assert_equals(multiply(BigInteger("5"), a).digits, [0])
    assert_equals(multiply(a, BigInteger("-5")).digits, [0])