def test_fill_value(self): self.assertNestedIterableEqual( divide(range(4), 6, fill='*'), [[0], [1], [2], [3], ['*'], ['*']], ) with self.assertRaises(TypeError): divide(range(4), 6, '*') self.assertNestedIterableEqual( divide(range(10), n=4, fill=0), [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 0, 0]], )
def test(self): self.assertEqual(divide(4), True) self.assertEqual(divide(2), False) self.assertEqual(divide(5), False) self.assertEqual(divide(88), True) self.assertEqual(divide(100), True) self.assertEqual(divide(67), False) self.assertEqual(divide(90), True) self.assertEqual(divide(10), True) self.assertEqual(divide(99), False) self.assertEqual(divide(32), True)
def gcd(a,b): try: [q, r] = divide(a,b) except ZeroDivisionError: zerodiv("b") while True: [q, r] = divide(a,b) if not r: break a,b = b,r return b
def test_uneven_parts(self): self.assertNestedIterableEqual( divide(range(10), 3), [[0, 1, 2, 3], [4, 5, 6], [7, 8, 9]] ) self.assertNestedIterableEqual( divide(range(10), 4), [[0, 1, 2], [3, 4, 5], [6, 7], [8, 9]] ) self.assertNestedIterableEqual( divide(range(8), 5), [[0, 1], [2, 3], [4, 5], [6], [7]] )
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])
def double(self, p): (xp, yp) = p # l, slope of the line l = divide(3 * pow(xp, 2) + 2 * self.a * xp + 1, 2 * yp, self.p) xr = (pow(l, 2, self.p) - self.a - xp - xp) % self.p yr = ((2*xp+xp+self.a)*l - pow(l, 3, self.p) - yp) % self.p return (xr, yr)
def test_divide_by_zero(self): ''' Test divide by zero ''' self.log_point() result = divide(self.int_x, self.zero) expected = 0 self.assertEqual(result, expected)
def test_divide_str_args(self): ''' Test with str args ''' self.log_point() result = divide(self.str_x, self.str_y) expected = 0 self.assertEqual(result, expected)
def test_divide_int_float_args(self): ''' Test with float and int args ''' self.log_point() result = divide(self.int_x, self.float_y) expected = .5 self.assertEqual(result, expected)
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)))
def power(a, b): int_or_float_check(a) int_or_float_check(b) if isinstance(b, int): if b == 0: return 1 elif b > 0: return int_power(a, b) elif b < 0: return divide(1, int_power(a, abs(b))) frac = get_fraction(b) if frac[0] > 0: first_step = int_power(a, frac[0]) result = int_root(first_step, frac[1]) return result elif frac[0] < 0: first_step = divide(1, int_power(a, abs(frac[0]))) result = int_root(first_step, frac[1]) return result
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
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
def exteuclid(a, b): try: [q, r] = divide(a, b) except ZeroDivisionError: zerodiv("b") matrix = [[0, 0], [0, 1], [1, 0]] wc = 2 # current working column while True: [q, r] = divide(a, b) matrix[0].append(q) matrix[1].append(matrix[0][wc] * matrix[1][wc - 1] + matrix[1][wc - 2]) matrix[2].append(matrix[0][wc] * matrix[2][wc - 1] + matrix[2][wc - 2]) if not r: break a, b = b, r wc = wc + 1 u = matrix[2][-2] v = -matrix[1][-2] return [u, v]
def add(self, p, q): if p == 0: return q if q == 0: return p if p == q: return self.double(p) (xp, yp) = p (xq, yq) = q # line y=lx+m through p and q l = divide(yq - yp, xq - xp, self.p) m = yp - l*xp xr = (pow(l, 2, self.p) - self.a - xp - xq) % self.p yr = -(l * xr + m) % self.p return xr, yr
def web_request(): x = int(request.args.get('x')) y = int(request.args.get('y')) result = divide(int(x), int(y)) output = { "error": False, "string": "%s%s%s=%s" % (x, "/", y, result), "answer": result } json_array = json.dumps(output) rep = flask.Response(json_array) rep.headers['Content-Type'] = "application/json" rep.headers['Access-Control-Allow-Origin'] = "*" return rep
def turn(self, aiTurn, isLeft): if aiTurn: if not divide.canDivide(self.chessqs, aiTurn): self.chessboard.scoreAI = divide.comePeople( self.chessqs, self.chessboard.scoreAI, aiTurn) else: if not divide.canDivide(self.chessqs, aiTurn): self.chessboard.scorePlayer = divide.comePeople( self.chessqs, self.chessboard.scorePlayer, aiTurn) deltaScore, hasQuan1, hasQuan2 = divide.divide(self.chessqs, self.chessQs, self.idxed, isLeft) self.chessQs[0].hasQuan = hasQuan1 self.chessQs[1].hasQuan = hasQuan2 return deltaScore
def kdtree(_input,depth=0): isleaf=True if len(_input)<2: return _input,isleaf _input2=[[i[0],i[2]] for i,j in _input] children=divide(zip(_input2,_input)) num_children=len(children) if num_children<2 and depth>0: return _input,isleaf isleaf=False result=[] for child in children: meta=child['meta'] _list=[i[1] for i in child['list']] result2,childisleaf=kdtree(_list,depth=depth+1) result.append({'meta':meta,'list':result2,'leaf':childisleaf}) if 0==depth: return result else: return result,isleaf
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
def run(Model, module_size=0, option="random", scipy=False): """ run liblinear training :param module_size: the data module for size for each model, 0 for no decomposition :param option: class, nothing, random :return: """ print("Reading data...") y, X, tag = readData(config.TRAIN_FILE, return_scipy=scipy) testY, testX, _ = readData(config.TEST_FILE, return_scipy=scipy) train = TrainWrapper(Model, config.LIBLINEAR_TRAINING_OPTIONS) print("Reading data completed.") if module_size > 0: sort_tag = 0 if option == 'class' else ( 1 if option == 'nothing' else 2) posXs, negXs = divide(tag, X, module_size, sort_tag=sort_tag) print("Dividing completed.") Xs, Ys = getData(posXs, negXs) minmax_shape = (len(posXs), len(negXs)) print("minmax shape: {}".format(minmax_shape)) plabels, pvals = list(zip(*parallel_train(train, Xs, Ys, testX=testX))) plabel, pval = minmax(pvals, plabels, minmax_shape) else: plabel, pval = train(X, y, testX=testX) # analysis assert len(plabel) == len(testY) total = len(testY) hit = 0 for idx, label in enumerate(plabel): if testY[idx] == label: hit += 1 print("Accuracy = {:.2f} ({}/{})".format(hit * 100 / total, hit, total)) saveResult("{}-{}-{}".format(Model.__name__, option, module_size), plabel, pval)
def test_zero_division(): with pytest.raises(ZeroDivisionError) as e_info: divide(4.0,0.0)
def test_divide_ints(): assert divide(4,2) == 2
from db_tools_jp import db_tools from divide import divide import math import datetime import pickle import jieba jieba.initialize() db = db_tools() db.connect() dv = divide() start_time = datetime.datetime.now() contents = db.read_table('news_data') #[(doc_id,'title','contents','source','time_capture','time_publish')...] db.close() N = len(contents) end_time = datetime.datetime.now() print(end_time - start_time) L_AVE = 0 for item in contents: try: L_AVE += len(item[1] + item[2]) except BaseException as e: pass L_AVE = L_AVE / N K1 = 1.5
def test_divide_positive_multi_digit(): result = divide(BigInteger("30"), BigInteger("2")) assert_equals(result, BigInteger("15"))
def test_neg_1_8(self): self.assertEqual(divide(-1, 99), "-0.(01)")
def test_neg_2_11(self): self.assertEqual(divide(-2, 11), "-0.(18)")
def test_divide_large(): a = BigInteger("96893488157419103232") b = BigInteger("48446744073709551616") result = divide(a, b) assert_equals(result, BigInteger("2"))
import divide x = divide.divide(1,0) print x
def test_integer_division(): assert divide(1, 2) != 0, "performed integer division"
num1 = int( input('Enter the first number to do {} : '.format(operation))) num2 = int( input('Enter the second number to do {} : '.format(operation))) except ValueError: print('Please enter an appropriate input to the place') continue if operation.lower() == 'addition': print(add(num1, num2)) elif operation.lower() == 'subtraction': print(subtract(num1, num2)) elif operation.lower() == 'multiplication': print(multiply(num1, num2)) elif operation.lower() == 'division': print(divide(num1, num2)) try: again = input("Do you want to do another calculation? (Y or N): ") if again.lower() != 'y' or again.lower() != 'y': print( 'Your answer must be either Y or N. It is note case sensetive.' ) print('Starting the progress again. Please enter the right value') continue except: print('There was an error try again') if again.lower() == 'y': print("Starting again") continue
def test_divide_floats(): assert divide(5.0, 2.0) == 2.5
def test_divide_ints(): assert divide(4, 2) == 2
def test_integer_division(): assert divide(1,2) != 0, "performed integer division"
def test_divide_smaller_dividend(): result = divide(BigInteger("3"), BigInteger("5")) assert_equals(result, BigInteger("0"))
def test_divide_remainder_result_positive(): result = divide(BigInteger("3"), BigInteger("2")) assert_equals(result, BigInteger("1"))
import add import divide import multiply import sub import sys input_1 = int(sys.argv[1]) input_2 = int(sys.argv[2]) print("1: Addition\n 2: Subtraction \n3: Multiply \n4: Divide") process = int(sys.argv[3]) if process == 1: add.add(input_1, input_2) elif process == 2: sub.subtract(input_1, input_2) elif process == 3: multiply.multiply(input_1, input_2) elif process == 4: divide.divide(input_1, input_2) else: print("Please select between 1 to 4 only")
def menu(): print("1-Addition \t\t 2-Subtration \t\t 3-Multiply \t\t 4-Division") print("5-Sin() \t\t 6-Cos() \t\t 7-Tan() \t\t 8-Sec()") print("9-Cosec() \t\t 10-Cot() \t\t 11-Square \t\t 12-Square Root \t\t") print("13-Power \t\t 14-Root \t\t 15-Expontial(e^x)") print("16-Factorial \t\t 17-log()\t\t 18-ln() \t\t 19-Quadratic Eq Solver") print( "20-Inverse(x^-1) \t 21-Sin inverse \t 22-Cos Inverse \t 23.Tan Inverse" ) print("24-Permutation \t\t 25-Combination \t 26-Percentage") print("27-Multiple Basic Operators At a time \t\t 28-Close") while True: try: choice = int(input("Enter your choice(press number):")) break except ValueError: print("Input must be a number!") if choice == 1: while True: Sum.Sum() x = int(input("press 1 to try again,press 2 to return to menu")) if x == 1: continue if x == 2: menu() break elif choice == 2: while True: Sub.sub() x = int(input("press 1 to try again,press 2 to return to menu")) if x == 1: continue if x == 2: menu() break elif choice == 3: while True: Mul.multiply() x = int(input("press 1 to try again,press 2 to return to menu")) if x == 1: continue if x == 2: menu() break elif choice == 4: while True: divide.divide() x = int(input("press 1 to try again,press 2 to return to menu")) if x == 1: continue if x == 2: menu() break elif choice == 5: while True: sin.sin() x = int(input("press 1 to try again,press 2 to return to menu")) if x == 1: continue if x == 2: menu() break elif choice == 6: while True: cos.cos() x = int(input("press 1 to try again,press 2 to return to menu")) if x == 1: continue if x == 2: menu() break elif choice == 7: while True: tan.tan() x = int(input("press 1 to try again,press 2 to return to menu")) if x == 1: continue if x == 2: menu() break elif choice == 8: while True: sec.sec() x = int(input("press 1 to try again,press 2 to return to menu")) if x == 1: continue if x == 2: menu() break elif choice == 9: while True: cosec.cosec() x = int(input("press 1 to try again,press 2 to return to menu")) if x == 1: continue if x == 2: menu() break elif choice == 10: while True: cot.cot() x = int(input("press 1 to try again,press 2 to return to menu")) if x == 1: continue if x == 2: menu() break elif choice == 11: while True: square.square() x = int(input("press 1 to try again,press 2 to return to menu")) if x == 1: continue if x == 2: menu() break elif choice == 12: while True: sqrt.sqrt() x = int(input("press 1 to try again,press 2 to return to menu")) if x == 1: continue if x == 2: menu() break elif choice == 13: while True: power.power() x = int(input("press 1 to try again,press 2 to return to menu")) if x == 1: continue if x == 2: menu() break elif choice == 14: while True: root.root() x = int(input("press 1 to try again,press 2 to return to menu")) if x == 1: continue if x == 2: menu() break elif choice == 15: while True: exponential.exponential() x = int(input("press 1 to try again,press 2 to return to menu")) if x == 1: continue if x == 2: menu() break elif choice == 16: while True: factorial.factorial() x = int(input("press 1 to try again,press 2 to return to menu")) if x == 1: continue if x == 2: menu() break elif choice == 17: while True: log.log() x = int(input("press 1 to try again,press 2 to return to menu")) if x == 1: continue if x == 2: menu() break elif choice == 18: while True: ln.ln() x = int(input("press 1 to try again,press 2 to return to menu")) if x == 1: continue if x == 2: menu() break elif choice == 19: while True: quadratic.quadratic() x = int(input("press 1 to try again,press 2 to return to menu")) if x == 1: continue if x == 2: menu() break elif choice == 20: while True: inverse.inv() x = int(input("press 1 to try again,press 2 to return to menu")) if x == 1: continue if x == 2: menu() break elif choice == 21: while True: asin.asin() x = int(input("press 1 to try again,press 2 to return to menu")) if x == 1: continue if x == 2: menu() break elif choice == 22: while True: acos.acos() x = int(input("press 1 to try again,press 2 to return to menu")) if x == 1: continue if x == 2: menu() break elif choice == 23: while True: atan.atan() x = int(input("press 1 to try again,press 2 to return to menu")) if x == 1: continue if x == 2: menu() break elif choice == 24: while True: per.per() x = int(input("press 1 to try again,press 2 to return to menu")) if x == 1: continue if x == 2: menu() break elif choice == 25: while True: com.com() x = int(input("press 1 to try again,press 2 to return to menu")) if x == 1: continue if x == 2: menu() break elif choice == 26: while True: percentage.percentage() x = int(input("press 1 to try again,press 2 to return to menu")) if x == 1: continue if x == 2: menu() break elif choice == 27: while True: combine() x = int(input("press 1 to try again,press 2 to return to menu")) if x == 1: continue if x == 2: menu() break elif choice == 28: close() else: print("Invalid Input.Try Again") menu()
def kdtree(_input, path=None, treemap=None, parentmeta=None, parent=None): _input=[n for n in _input] if None == treemap: # root treemap = {} path = [] node = Node() node.parent = parent node.path = path depth = len(path) if len(_input) < 2: node.leaf = True node.overlap = False node.content = _input node.key = _input[0][1] else: _input2 = [[pos[depth % 2], pos[depth % 2 + 2]] for pos, _, _ in _input] # column first children = divide(zip(_input2, _input)) if len(children) < 2 and depth > 0: node.leaf = True node.overlap = True node.content = _input else: node.leaf = False node.children = [] for child, i in zip(children, range(len(children))): children_path = path + [i] _list = [i[1] for i in child] node_child = kdtree(_list, path=children_path, treemap=treemap, parent=node) node.children.append(node_child) if node_child.overlap: node.overlap = True if node.leaf: for _, key, pos in node.content: treemap[key] = node children_pos = [pos for _, key, pos in node.content] else: children_pos = [_child.position for _child in node.children] node.key = node.children[0].key minx, miny = 10**6, 10**6 maxx, maxy = -10**6, -10**6 for pos in children_pos: minx = min(minx, pos[0]) miny = min(miny, pos[1]) maxx = max(maxx, pos[2]) maxy = max(maxy, pos[3]) node.position = [minx, miny, maxx, maxy] if 0 == depth: _node = Node() _node.position = [i for i in node.position] _node.overlap = node.overlap _node.path = [0] _node.children = [node] node.parent = _node __node = Node() __node.position = [i for i in node.position] __node.overlap = node.overlap __node.path = [] __node.children = [_node] _node.parent = __node return __node, treemap else: return node
def test_4_2(self): self.assertEqual(divide(4, 2), "2")
def test_divide_remainder_result_negative(): result = divide(BigInteger("-3"), BigInteger("2")) assert_equals(result, BigInteger("-1")) result = divide(BigInteger("3"), BigInteger("-2")) assert_equals(result, BigInteger("-1"))
def test_divide(): assert divide(3, 4) == 0.75
def test_divide_zero(): # if it acts like python, it should raise an exception with pytest.raises(ZeroDivisionError): divide(3, 0)
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)
def test_zero_division(): with pytest.raises(ZeroDivisionError) as e_info: divide(4.0, 0.0)