def generate_problem(): operators = ["-", "+", "*", ":"] correct_answer = 0 number1 = random.randint(-10, 10) number2 = random.randint(-10, 10) selected_operator = random.choice(operators) while True: try: operator.div(number1, number2) break except ZeroDivisionError: # print "division by zero not allowed" # print number2 number1 = random.randint(-10, 10) number2 = random.randint(-10, 10) print "Solve the following problem {0} {1} {2}".format( number1, selected_operator, number2) correct_answer = ops[selected_operator](number1, number2) if selected_operator == ":": # print selected_operator correct_answer = float(number1) / number2 # print correct_answer if number1 % number2 == 0: correct_answer = int(number1 / number2) # print "i am in if" else: correct_answer = round(correct_answer, 2) # print "i am in else" # print correct_answer problem = str(number1) + " " + selected_operator + " " + str( number2) + "=" + str(correct_answer) return problem, correct_answer
def testAverageNormals(poly): # These logs are commented out because they slow down the script considerably. They are for debugging purposes. # Application.LogMessage("Working from polygon index %s" % poly.index) oAdjacentPolys = poly.GrowNeighborPolygons(oTargetGrowAmount) XYZListCount = 0 oNormalXList = 0 oNormalYList = 0 oNormalZList = 0 for polys in oAdjacentPolys: oPolysNode = polys.Nodes(0) oPolysNormal = oPolysNode.Normal oNormalXList+=(oPolysNode.Normal.X) oNormalYList+=(oPolysNode.Normal.Y) oNormalZList+=(oPolysNode.Normal.Z) XYZListCount+=1 # Application.LogMessage("%(what)s %(numb)s is a polygon adjacent to the current one with normal %(nx)s, %(ny)s, %(nz)s" % {"numb":polys.index,"what":polys.Type,"nx":oPolysNormal.X,"ny":oPolysNormal.Y,"nz":oPolysNormal.Z}) oAverageNormalX = div(oNormalXList,XYZListCount) oAverageNormalY = div(oNormalYList,XYZListCount) oAverageNormalZ = div(oNormalZList,XYZListCount) NormalXRef = poly.Nodes(0).Normal.X NormalYRef = poly.Nodes(0).Normal.Y NormalZRef = poly.Nodes(0).Normal.Z deltax = abs(oAverageNormalX-NormalXRef) deltay = abs(oAverageNormalY-NormalYRef) deltaz = abs(oAverageNormalZ-NormalZRef) # Application.LogMessage("Total Normal delta for poly index %(polyindex)s is %(deltasum)s" % {"polyindex":poly.index,"deltasum":(deltax+deltay+deltaz)}) if ((deltax+deltay+deltaz)>oNormalReverseThreshold): return 1 else: return 0
def __div__(self, other): if type(other) in (int, long, float): return self.__class__(operator.div(self.X, other), operator.div(self.Y, other), operator.div(self.Z, other)) else: raise TypeError("Divider must be instance of (int, long, or float). '%s' given." % other.__class__.__name__)
def __rdiv__(self, other): try: return Vector2(operator.div(other[0], self[0]), operator.div(other[1], self[1])) except TypeError: return Vector2(operator.div(other, self[0]), operator.div(other, self[1]))
def __div__(self, other): try: return Vector2d(operator.div(self.x, other.x), operator.div(self.y, other.y)) except: return Vector2d(operator.div(self.x, other), operator.div(self.y, other))
def doprob(): op = choice('+-*/') nums = [randint(1,10) for i in range(2)] nums.sort(reverse=True) if op != '/': ans = ops[op](*nums) pr = '%d %s %d =' % (nums[0],op,nums[1]) else: ans = div(nums[0],nums[1]) if div (nums[0] * 10,nums[1]) ==ans * 10: pr = '%d %s %d = ' %(nums[0],op,nums[1]) else: ans = mul(num[0],nums[1]) pr = '%d %s %d =' (nums[0], ' *',nums[1]) opps =0 while True: try: if int(raw_input(pr)) == ans: print 'correct' break if opps == MAXTRIES: print 'answer\n %s%d'%(pr,ans) else: print 'incorrect ...try again' opps +=1 except (KeyboardInterrupt, \ EOFError,ValueError): print 'invalid input...try again'
def check_for_collisions(self, coll_layer): for fish in self.fish_list: tile_x = int(operator.div((fish.cx + self.rel_offset_x), coll_layer.tilewidth)) tile_y = int(operator.div((fish.cy + self.rel_offset_y), coll_layer.tileheight)) #print(tile_x, tile_y) #print(fish.cx + self.rel_offset_x, fish.cy + self.rel_offset_y) if coll_layer.content2D[tile_y][tile_x] is not None: print("collision occured")
def test_div(self): other = mock.MagicMock() self.assertEqual(operator.div(self.proxy, other), operator.div(self.obj, other)) self.assertEqual(self.proxy.__div__(other), operator.div(self.obj, other)) self.assertEqual(operator.div(proxy(4.5), 2), 2.25) self.assertEqual(operator.div(proxy(5), 2), 2)
def test_div(self): u, = initVariablesADI(np.array([[1]])) # uses "classic" division even if future division is enabled. import operator with pytest.raises(DeprecationWarning): operator.div(u, 5) with pytest.raises(DeprecationWarning): operator.div(5, u)
def __div__(self, other): if isinstance(other, (int, long, float)): return self.__class__(operator.div(self.X, other), operator.div(self.Y, other)) else: raise TypeError( "Divider must be instance of (int, long, or float). '%s' given." % other.__class__.__name__)
def palindrome_count(p): """Compute the number of palindromes we can form with the elements of p. """ c = Counter(p) halves = [div(v, 2) for v in c.values() if v > 1] singleCount = sum([1 for v in c.values() if v % 2 == 1]) num = factorial(sum(halves)) denom = reduce(mul, map(factorial, halves), 1) return 0 if singleCount > 1 else div(num, denom) * max(1, singleCount)
def test_z_div_truediv_delay_over_constant(self, a): div_filter = operator.div(z ** -1, a) truediv_filter = operator.truediv(z ** -1, a) div_expected = it.imap(lambda x: operator.div(x, a), [0.] + self.data[:-1]) truediv_expected = it.imap(lambda x: operator.truediv(x, a), [0.] + self.data[:-1]) assert almost_eq(div_filter(self.data), div_expected) assert almost_eq(truediv_filter(self.data), truediv_expected)
def __div__(self, other): if isinstance(other, Poly): if len(other) == 1: delta, value = other.data.items()[0] return Poly({(k - delta): operator.div(v, other) for k, v in self.data.iteritems()}) raise NotImplementedError("Can't divide general Poly instances") return Poly({k: operator.div(v, other) for k, v in self.data.iteritems()})
def test_rdiv(self): """ Verify that __rdiv__ is redirected to the proxiee. """ other = mock.Mock() self.assertEqual(operator.div(other, self.proxy), operator.div(other, self.obj)) self.assertEqual(self.proxy.__rdiv__(other), operator.div(other, self.obj)) self.assertEqual(operator.div(4.5, proxy(2)), 2.25) self.assertEqual(operator.div(5, proxy(2)), 2)
def pedout(indi, gen, max, top, bot) : if indi and le(gen,max) : gen = add(1,gen) fath = father(indi) moth = mother(indi) height = add(1,sub(bot,top)) offset = div(sub(height,8),2) block(indi,add(top,offset),mul(10,sub(gen,2))) half = div(height,2) pedout(fath,gen,max,top,sub(add(top,half),1)) pedout(moth,gen,max,add(top,half),bot)
def DisplayItem(self, SelectLeftChar): Period = int(self.Repeat.total_seconds()) Seconds = operator.mod(Period, 60) Period = operator.div(Period, 60) Minutes = operator.mod(Period, 60) Period = operator.div(Period, 60) Hours = operator.mod(Period, 24) Period = operator.div(Period, 24) Days = Period print("{}{:^19}".format(SelectLeftChar, self.ScheduleDate.strftime("%Y-%m-%d %H:%M:%S")) + "\r") print("{}{:>2}={:<2} {:>3} {:0>2}:{:0>2}:{:0>2}".format(SelectLeftChar, self.RelayNumber, self.RelayState, str(Days), str(Hours), str(Minutes), str(Seconds)) + "\r")
def DisplayItem(self, SelectLeftChar): Period = int(self.Repeat.total_seconds()) Seconds = operator.mod(Period, 60) Period = operator.div(Period, 60) Minutes = operator.mod(Period, 60) Period = operator.div(Period, 60) Hours = operator.mod(Period, 24) Period = operator.div(Period, 24) Days = Period print("{}{:^19}".format( SelectLeftChar, self.ScheduleDate.strftime("%Y-%m-%d %H:%M:%S")) + "\r") print("{}{:>2}={:<2} {:>3} {:0>2}:{:0>2}:{:0>2}".format( SelectLeftChar, self.RelayNumber, self.RelayState, str(Days), str(Hours), str(Minutes), str(Seconds)) + "\r")
def divide(*args): """ Returns a STRING with the sum of the arguments """ # TODO: Fill sum with the correct value, based on the # args provided. quotient = "1" try: operator.div(args[0], args[1]) except ZeroDivisionError: status = "404 Not Found" body = "<h1>Divisor cannot be zero</h1>" print("ZeroDivisionError") finally: return quotient
def showImage(self): resizeX = operator.div(1366, self.dimension[0]) resizeY = operator.div(768, self.dimension[1]) if(resizeX > resizeY): resize = resizeY else: resize = resizeX if(resize == 0): resize = 1 resizedImg = self.image.resize((self.dimension[0]*resize, self.dimension[1]*resize)) resizedImg.show()
def __idiv__(self, other): from operator import div self.assert_same_length(other) for i in range(len(self)): self[i] = div(self[i], other[i]) return self
def KeysAddSchedule(self, KeyCode): Result = KeyCode self.InputBuffer = self.KeyMaskedInput("####-##-## ##:##:## ### ##:##:## ## #", self.InputBuffer, KeyCode) # If enter key is pressed, change to display main menu. if KeyCode == 10: # If full user input has been gathered, add a schedule item. if len(self.InputBuffer) == 26: # Parse user input. UserInput = self.GetMaskedInput("####-##-## ##:##:## ### ##:##:## ## #", self.InputBuffer) RelayState = { "0":ScheduleItem.RELAY_OFF, "1":ScheduleItem.RELAY_ON, "2":ScheduleItem.RELAY_TOGGLE, }.get(UserInput[36:37], ScheduleItem.RELAY_TOGGLE) PeriodSeconds = string.atoi(UserInput[30:32]) + 60 * string.atoi(UserInput[27:29]) + 60 * 60 * string.atoi(UserInput[24:26]) + 24 * 60 * 60 * string.atoi(UserInput[20:23]) PeriodDays = operator.div(PeriodSeconds, 24 * 60 * 60) PeriodSeconds = operator.mod(PeriodSeconds, 24 * 60 * 60) # Add schedule item, ignore errors from invalid data entered. try: self.ThisSchedule.AddSchedule(string.atoi(UserInput[33:35]), datetime.datetime(string.atoi(UserInput[0:4]), string.atoi(UserInput[5:7]), string.atoi(UserInput[8:10]), string.atoi(UserInput[11:13]), string.atoi(UserInput[14:16]), string.atoi(UserInput[17:19])), RelayState, datetime.timedelta(PeriodDays, PeriodSeconds)) except: print("") self.ThisWindow.refresh() self.SetInterfaceState(STATE_MAIN_MENU) return Result
def run(): primes = prime_reader.read_primes_default() last_prime = primes.next() prime_count = 0 diag_total = 1 current = 1 for ring in eu.numbers(2): incr = (ring - 1) * 2 for corner in xrange(3): current = op.iadd(current, incr) while current > last_prime: last_prime = primes.next() if current == last_prime: prime_count = op.iadd(prime_count, 1) current = op.add(current, incr) diag_total = op.iadd(diag_total, 4) perc = op.div(float(prime_count), diag_total) # print ring, side_length(ring), last_prime, diag_total, perc if op.lt(perc, 0.1): return side_length(ring)
def test_operators(self): assert (Q > 1).eval_(2) assert (Q >= 1).eval_(1) assert (Q <= 1).eval_(1) assert (Q < 1).eval_(0) assert (Q == 1).eval_(1) assert (Q != 1).eval_(2) assert not (Q > 1).eval_(1) assert not (Q >= 1).eval_(0) assert not (Q <= 1).eval_(2) assert not (Q < 1).eval_(1) assert not (Q == 1).eval_(2) assert not (Q != 1).eval_(1) assert (Q <= Q).eval_(5) assert (Q + 5).eval_(2) == 7 assert (Q - 1).eval_(1) == 0 assert (Q * 2).eval_(4) == 8 if not PY3: assert operator.div(Q, 2).eval_(3) == 1 assert operator.truediv(Q, 2).eval_(3) == 1.5 assert (Q / 2).eval_(4) == 2.0 assert (Q // 2).eval_(4) == 2 assert (Q % 2).eval_(3) == 1 assert (Q**2).eval_(3) == 9
def evaluate(self): result = None left = self.left.evaluate() right = self.right.evaluate() if self.operation == '+': result = operator.add(left, right) elif self.operation == '-': result = operator.sub(left, right) elif self.operation == '*': result = operator.mul(left, right) elif self.operation == '/': result = operator.div(left, right) elif self.operation == '^': result = operator.pow(left, right) elif self.operation == 'and': result = left and right elif self.operation == 'or': result = left or right elif self.operation == '<': result = operator.lt(left, right) elif self.operation == '<=': result = operator.le(left, right) elif self.operation == '==': result = operator.eq(left, right) elif self.operation == '!=': result = operator.ne(left, right) elif self.operation == '>': result = operator.gt(left, right) elif self.operation == '>=': result = operator.ge(left, right) elif self.operation == 'in': result = (left in right) return result
def check_previous_stocks(): """ This functions loops through our trades stored in memory and returns volumn weighted stock price and all share index :return: dict """ timestamp_15 = time.time() - 900 sum_trade_quantity = 0 sum_quantity = 0 price_sum = 1 for i in last_trades: price_sum *= last_trades[i]["price"] if i >= timestamp_15: sum_trade_quantity += operator.mul(last_trades[i]["quantity"], last_trades[i]["price"]) sum_quantity += last_trades[i]["quantity"] try: return { "weighted_stock_price": round(operator.div(sum_trade_quantity, sum_quantity), 2), "all_share_index": price_sum**(1 / float(len(last_trades))) } except ZeroDivisionError: return {"weighted_stock_price": 0, "all_share_index": 0}
def get_ellipse_table(y_radius): global ellipses_table if ellipses_table.has_key(y_radius): return ellipses_table[y_radius] x_radius = y_radius / 2 ellipse_table = {} split_point = y_radius - 0.5 for y in range(y_radius, 0, -1): yy = y * y val1 = operator.div(yy, float(y_radius * y_radius)) val2 = operator.sub(1.0, val1) x_squared = (float(x_radius * x_radius)) * val2 x_offset_float = math.sqrt(operator.abs(x_squared)) x_offset = int(math.ceil(x_offset_float)) y_offset = operator.abs(y - y_radius) ellipse_table[y_offset] = x_offset ellipse_table[int(2 * split_point) - y_offset] = x_offset pair = (ellipse_table, x_radius) ellipses_table[y_radius] = pair return pair
def get_ellipse_table(y_radius): global ellipses_table if ellipses_table.has_key(y_radius): return ellipses_table[y_radius] x_radius = y_radius / 2 ellipse_table = {} split_point = y_radius - 0.5 for y in range(y_radius, 0, -1): yy = y * y val1 = operator.div(yy, float(y_radius * y_radius)) val2 = operator.sub(1.0, val1) x_squared = (float(x_radius * x_radius)) * val2 x_offset_float = math.sqrt(operator.abs(x_squared)) x_offset = int(math.ceil(x_offset_float)) y_offset = operator.abs(y - y_radius) ellipse_table[y_offset] = x_offset ellipse_table[int(2*split_point) - y_offset] = x_offset pair = (ellipse_table, x_radius) ellipses_table[y_radius] = pair return pair
def test_operators(self): assert (Q > 1).eval_(2) assert (Q >= 1).eval_(1) assert (Q <= 1).eval_(1) assert (Q < 1).eval_(0) assert (Q == 1).eval_(1) assert (Q != 1).eval_(2) assert not (Q > 1).eval_(1) assert not (Q >= 1).eval_(0) assert not (Q <= 1).eval_(2) assert not (Q < 1).eval_(1) assert not (Q == 1).eval_(2) assert not (Q != 1).eval_(1) assert (Q <= Q).eval_(5) assert (Q + 5).eval_(2) == 7 assert (Q - 1).eval_(1) == 0 assert (Q * 2).eval_(4) == 8 if not PY3: assert operator.div(Q, 2).eval_(3) == 1 assert operator.truediv(Q, 2).eval_(3) == 1.5 assert (Q / 2).eval_(4) == 2.0 assert (Q // 2).eval_(4) == 2 assert (Q % 2).eval_(3) == 1 assert (Q ** 2).eval_(3) == 9
def __div__(self, other): if isinstance(other, ZFilter): return ZFilter(self.numpoly * other.denpoly, self.denpoly * other.numpoly) if isinstance(other, LinearFilter): raise ValueError("Filter equations have different domains") return self * operator.div(1, other)
def test_z_div_truediv_constant_over_delay(self, a): div_inv_filter = operator.div(a, 1 + z**-1) truediv_inv_filter = operator.truediv(a, 1 + z**-1) expected = [a * x for x in self.data] for idx in xrange(1, len(expected)): expected[idx] -= expected[idx - 1] assert almost_eq(div_inv_filter(self.data), expected) assert almost_eq(truediv_inv_filter(self.data), expected)
def test_z_div_truediv_constant_over_delay(self, a): div_inv_filter = operator.div(a, 1 + z ** -1) truediv_inv_filter = operator.truediv(a, 1 + z ** -1) expected = [a*x for x in self.data] for idx in xrange(1,len(expected)): expected[idx] -= expected[idx-1] assert almost_eq(div_inv_filter(self.data), expected) assert almost_eq(truediv_inv_filter(self.data), expected)
def read_datetime(self): # Initiate DS1302 communication. self.InitiateDS1302() # Write address byte. self.WriteByte(int("10111111", 2)) # Read date and time data. Byte = self.ReadByte() second = operator.mod(Byte, 16) + operator.div(Byte, 16) * 10 Byte = self.ReadByte() minute = operator.mod(Byte, 16) + operator.div(Byte, 16) * 10 Byte = self.ReadByte() hour = operator.mod(Byte, 16) + operator.div(Byte, 16) * 10 Byte = self.ReadByte() day = operator.mod(Byte, 16) + operator.div(Byte, 16) * 10 Byte = self.ReadByte() month = operator.mod(Byte, 16) + operator.div(Byte, 16) * 10 Byte = self.ReadByte() _ = (operator.mod(Byte, 16) + operator.div(Byte, 16) * 10) - 1 Byte = self.ReadByte() year = 2000 + operator.mod(Byte, 16) + operator.div(Byte, 16) * 10 dt = datetime(year, month, day, hour, minute, second) # End DS1302 communication. self.EndDS1302() return dt
def WriteDateTime(self, Year, Month, Day, DayOfWeek, Hour, Minute, Second): # Initiate DS1302 communication. self.InitiateDS1302() # Write address byte. self.WriteByte(int("10111110", 2)) # Write seconds data. self.WriteByte( operator.mod(Second, 10) | operator.div(Second, 10) * 16) # Write minute data. self.WriteByte( operator.mod(Minute, 10) | operator.div(Minute, 10) * 16) # Write hour data. self.WriteByte(operator.mod(Hour, 10) | operator.div(Hour, 10) * 16) # Write day data. self.WriteByte(operator.mod(Day, 10) | operator.div(Day, 10) * 16) # Write month data. self.WriteByte(operator.mod(Month, 10) | operator.div(Month, 10) * 16) # Write day of week data. self.WriteByte( operator.mod(DayOfWeek, 10) | operator.div(DayOfWeek, 10) * 16) # Write year of week data. self.WriteByte(operator.mod(Year, 10) | operator.div(Year, 10) * 16) # Make sure write protect is turned off. self.WriteByte(int("00000000", 2)) # Make sure trickle charge mode is turned off. self.WriteByte(int("00000000", 2)) # End DS1302 communication. self.EndDS1302()
def ReadDateTime(self, DateTime): # Initiate DS1302 communication. self.InitiateDS1302() # Write address byte. self.WriteByte(int("10111111", 2)) # Read date and time data. Data = "" Byte = self.ReadByte() DateTime["Second"] = operator.mod(Byte, 16) + operator.div(Byte, 16) * 10 Byte = self.ReadByte() DateTime["Minute"] = operator.mod(Byte, 16) + operator.div(Byte, 16) * 10 Byte = self.ReadByte() DateTime["Hour"] = operator.mod(Byte, 16) + operator.div(Byte, 16) * 10 Byte = self.ReadByte() DateTime["Day"] = operator.mod(Byte, 16) + operator.div(Byte, 16) * 10 Byte = self.ReadByte() DateTime["Month"] = operator.mod(Byte, 16) + operator.div(Byte, 16) * 10 Byte = self.ReadByte() DateTime["DayOfWeek"] = (operator.mod(Byte, 16) + operator.div(Byte, 16) * 10) - 1 Byte = self.ReadByte() DateTime["Year"] = operator.mod(Byte, 16) + operator.div(Byte, 16) * 10 Data = self.DOW[DateTime["DayOfWeek"]] + " " + format(DateTime["Year"] + 2000, "04d") + "-" + format(DateTime["Month"], "02d") + "-" + format(DateTime["Day"], "02d") Data += " " + format(DateTime["Hour"], "02d") + ":" + format(DateTime["Minute"], "02d") + ":" + format(DateTime["Second"], "02d") # End DS1302 communication. self.EndDS1302() return Data
def WriteDateTime(self, Year, Month, Day, DayOfWeek, Hour, Minute, Second): # Initiate DS1302 communication. self.InitiateDS1302() # Write address byte. self.WriteByte(int("10111110", 2)) # Write seconds data. self.WriteByte(operator.mod(Second, 10) | operator.div(Second, 10) * 16) # Write minute data. self.WriteByte(operator.mod(Minute, 10) | operator.div(Minute, 10) * 16) # Write hour data. self.WriteByte(operator.mod(Hour, 10) | operator.div(Hour, 10) * 16) # Write day data. self.WriteByte(operator.mod(Day, 10) | operator.div(Day, 10) * 16) # Write month data. self.WriteByte(operator.mod(Month, 10) | operator.div(Month, 10) * 16) # Write day of week data. self.WriteByte(operator.mod(DayOfWeek, 10) | operator.div(DayOfWeek, 10) * 16) # Write year of week data. self.WriteByte(operator.mod(Year, 10) | operator.div(Year, 10) * 16) # Make sure write protect is turned off. self.WriteByte(int("00000000", 2)) # Make sure trickle charge mode is turned off. self.WriteByte(int("00000000", 2)) # End DS1302 communication. self.EndDS1302()
def __str__(self): import operator ret = str (self.time) + ' (' + str(operator.div(self.time, 60)) + ':' + str(self.time % 60) + ') ' + \ self.stationName[self.station] + ' ' if self.status == AVAILABLE: ret = ret + "AVAIL" else: ret = ret + "NEED" return ret
def test_operators_combine(self): def _check_fill(meth, op, a, b, fill_value=0): exp_index = a.index.union(b.index) a = a.reindex(exp_index) b = b.reindex(exp_index) amask = isnull(a) bmask = isnull(b) exp_values = [] for i in range(len(exp_index)): if amask[i]: if bmask[i]: exp_values.append(nan) continue exp_values.append(op(fill_value, b[i])) elif bmask[i]: if amask[i]: exp_values.append(nan) continue exp_values.append(op(a[i], fill_value)) else: exp_values.append(op(a[i], b[i])) result = meth(a, b, fill_value=fill_value) expected = Series(exp_values, exp_index) assert_series_equal(result, expected) a = Series([nan, 1., 2., 3., nan], index=np.arange(5)) b = Series([nan, 1, nan, 3, nan, 4.], index=np.arange(6)) pairings = [] for op in ['add', 'sub', 'mul', 'pow', 'truediv', 'floordiv']: fv = 0 lop = getattr(Series, op) lequiv = getattr(operator, op) rop = getattr(Series, 'r' + op) # bind op at definition time... requiv = lambda x, y, op=op: getattr(operator, op)(y, x) pairings.append((lop, lequiv, fv)) pairings.append((rop, requiv, fv)) if compat.PY3: pairings.append((Series.div, operator.truediv, 1)) pairings.append( (Series.rdiv, lambda x, y: operator.truediv(y, x), 1)) else: pairings.append((Series.div, operator.div, 1)) pairings.append((Series.rdiv, lambda x, y: operator.div(y, x), 1)) for op, equiv_op, fv in pairings: result = op(a, b) exp = equiv_op(a, b) assert_series_equal(result, exp) _check_fill(op, equiv_op, a, b, fill_value=fv) # should accept axis=0 or axis='rows' op(a, b, axis=0)
def grant(self): """ do grant """ logger.info( '=================== start to grant =================== \n') pre_grant_amount = 0 self.pre_process() def _get_weight(weight_map, feature, code): if not weight_map or not isinstance(weight_map, dict): return 1.0 feature_option_map = weight_map.get(feature, {}) return feature_option_map.get(code, 1.0) option_weight_map = self.dao.get_option_weight(self.name) feature_val_weight = { feature: _get_weight(option_weight_map, feature, val) for feature, val in self.feature_library.iteritems() } annual_income = self.feature_context.get_data('annual_income') feature_val_weight.update({'annual_income': annual_income}) sub_level = self.dao.get_sub_level(self.name, annual_income) if sub_level is not None: pre_grant_amount_str = sub_level.computational_formula % feature_val_weight pre_grant_amount_str = '%s * %s' % (sub_level.coefficient, pre_grant_amount_str) pre_grant_amount = eval(pre_grant_amount_str) try: pre_grant_amount = int(float(str(pre_grant_amount))) except ValueError: pre_grant_amount = int(pre_grant_amount) logger.info('level is %s', sub_level) logger.info( '\n\t===> model feature value weight map=%s\n\n\tannual_income=%s\n\n\tpre_grant_amount=%s', feature_val_weight, annual_income, pre_grant_amount) # calibration result if operator.lt(pre_grant_amount, 5288): pre_grant_amount = 5288 elif operator.lt(pre_grant_amount, 200000) and operator.ge( pre_grant_amount, 5288): pre_grant_amount = operator.mul( operator.div(pre_grant_amount, 100), 100) else: pre_grant_amount = 200000 if operator.lt(pre_grant_amount, 5288): pre_grant_amount = 5288 logger.info( 'calibration result pre_grant_amount=%s\n\n' '=================== end to grant =================== \n', pre_grant_amount) return pre_grant_amount
def getDelta(v, ra, dec, stat, Nnear=10): vo = stat(v) stdv = numpy.std(v) results = [Near(v, ra, dec, x, y, stat, Nnear) for x, y in izip(ra, dec)] vnear, snear = numpy.transpose(results) #delta = numpy.sqrt(Nnear)/stdv * numpy.hypot(vnear-vo, snear-stdv) delta = operator.mul(operator.div(numpy.sqrt(Nnear), stdv), numpy.hypot(vnear-vo, snear-stdv)) return delta, sum(delta)
def easyCalcs(t, x, y): calculation = { '+': lambda: operator.add(x, y), '*': lambda: operator.mul(x, y), '-': lambda: operator.sub(x, y), '/': lambda: operator.div(x, y), '%': lambda: operator.mod(x, y) } return calculation[t]()
def test_operators_combine(self): def _check_fill(meth, op, a, b, fill_value=0): exp_index = a.index.union(b.index) a = a.reindex(exp_index) b = b.reindex(exp_index) amask = isnull(a) bmask = isnull(b) exp_values = [] for i in range(len(exp_index)): if amask[i]: if bmask[i]: exp_values.append(nan) continue exp_values.append(op(fill_value, b[i])) elif bmask[i]: if amask[i]: exp_values.append(nan) continue exp_values.append(op(a[i], fill_value)) else: exp_values.append(op(a[i], b[i])) result = meth(a, b, fill_value=fill_value) expected = Series(exp_values, exp_index) assert_series_equal(result, expected) a = Series([nan, 1., 2., 3., nan], index=np.arange(5)) b = Series([nan, 1, nan, 3, nan, 4.], index=np.arange(6)) pairings = [] for op in ['add', 'sub', 'mul', 'pow', 'truediv', 'floordiv']: fv = 0 lop = getattr(Series, op) lequiv = getattr(operator, op) rop = getattr(Series, 'r' + op) # bind op at definition time... requiv = lambda x, y, op=op: getattr(operator, op)(y, x) pairings.append((lop, lequiv, fv)) pairings.append((rop, requiv, fv)) if compat.PY3: pairings.append((Series.div, operator.truediv, 1)) pairings.append((Series.rdiv, lambda x, y: operator.truediv(y, x), 1)) else: pairings.append((Series.div, operator.div, 1)) pairings.append((Series.rdiv, lambda x, y: operator.div(y, x), 1)) for op, equiv_op, fv in pairings: result = op(a, b) exp = equiv_op(a, b) assert_series_equal(result, exp) _check_fill(op, equiv_op, a, b, fill_value=fv) # should accept axis=0 or axis='rows' op(a, b, axis=0)
def factorize(n: int) -> Counter: i, c = 2, Counter() while i * i <= n: while n % i == 0: n = div(n, i) c[i] += 1 i += (i & 1) + 1 if n != 1: c[n] += 1 return c
def calculate_pe_ratio(self): """ Calculates PE ratio for the stock provided in input :return: float """ try: return operator.div(self.market_price, self.stock_details["last_divident"]) except ZeroDivisionError: return 0
def check(a, b): _check_op(a, b, operator.add) _check_op(a, b, operator.sub) _check_op(a, b, operator.div) _check_op(a, b, operator.mul) _check_op(a, b, lambda x, y: operator.add(y, x)) _check_op(a, b, lambda x, y: operator.sub(y, x)) _check_op(a, b, lambda x, y: operator.div(y, x)) _check_op(a, b, lambda x, y: operator.mul(y, x))
def ask_questions(p = []): """ Generates equations for the player to solve based on the randomly generated numbers. p is the problem array. Returns the number of questions asked. """ number_of_questions_asked = 0 correct_answers = 0 minimum_questions_asked = sqrt(len(p)) while len(p) > 1 or correct_answers < minimum_questions_asked: # grab two random numbers. first_number = choice(p) second_number = choice(p) # grab an operation randomly operation = choice(operations) print "%s %s %s = ?" % (first_number, operation, second_number) number_of_questions_asked += 1 answer = 0 if operation == "+": answer = operator.add(first_number, second_number) elif operation == "-": answer = operator.sub(first_number, second_number) elif operation == "*": answer = operator.mul(first_number, second_number) elif operation == "/": answer = operator.div(first_number, second_number) else: answer = operator.mod(first_number, second_number) player_answer = raw_input("> ") while not is_number(player_answer): print "That is not a number! Please enter a valid number." player_answer = raw_input("> ") if int(player_answer) == answer: correct_answers += 1 p.remove(first_number) # If there are two numbers which are equal in the list, # only remove one of them if first_number != second_number: p.remove(second_number) return number_of_questions_asked
def ask_questions(self): """ Generates equations for the player to solve based on the randomly generated numbers. This returns the number of questions asked, along with the time it took to ask the necessary questions. """ number_of_questions_asked = 0 correct_answers = 0 minimum_questions_asked = math.sqrt(len(self.problems)) start_time = time.time() while len(self.problems) > 1 or correct_answers < minimum_questions_asked: # Grab two random numbers. a = choice(self.problems) # Leveraging random lib b = choice(self.problems) operation = choice(self.operations) print "%s %s %s = ?" % (a, operation, b) number_of_questions_asked += 1 answer = 0 if operation == "+": answer = operator.add(a, b) elif operation == "-": answer = operator.sub(a, b) elif operation == "*": answer = operator.mul(a, b) elif operation == "/": answer = operator.div(a, b) else: answer = operator.mod(a, b) player_answer = raw_input("> ") while not is_number(player_answer): print "%s is not a number! Please enter a valid number." % (player_answer) player_answer = raw_input("> ") if player_answer == str(answer): correct_answers += 1 self.problems.remove(a) # If there are two numbers which are equal in problems, # only remove one of them. if a != b: self.problems.remove(b) return (number_of_questions_asked, time.time() - start_time)
def evalRPN(self, tokens: List[str]) -> int: oper = {'+': add, '-': sub, '*': mul, '/': lambda x, y: int(div(x, y))} stack = [] for tok in tokens: if tok in oper: y = stack.pop() x = stack.pop() res = oper[tok](x, y) else: res = int(tok) stack.append(res) return stack[0]
def WriteByte(self, Byte): for Count in range(8): time.sleep(self.CLK_PERIOD) RPi.GPIO.output(self.RTC_DS1302_SCLK, 0) Bit = operator.mod(Byte, 2) Byte = operator.div(Byte, 2) time.sleep(self.CLK_PERIOD) RPi.GPIO.output(self.RTC_DS1302_IO, Bit) time.sleep(self.CLK_PERIOD) RPi.GPIO.output(self.RTC_DS1302_SCLK, 1)
def test_arithmetic_with_null(self): l, r = Scalar(1), Null() assert isinstance(l + r, Null) assert isinstance(l - r, Null) assert isinstance(l * r, Null) assert isinstance(l / r, Null) assert isinstance(l // r, Null) assert isinstance(l ** r, Null) assert isinstance(l % r, Null) if not PY3: assert isinstance(operator.div(l, r), Null)
def check(other): _check_op(other, operator.add) _check_op(other, operator.sub) _check_op(other, operator.div) _check_op(other, operator.mul) _check_op(other, operator.pow) _check_op(other, lambda x, y: operator.add(y, x)) _check_op(other, lambda x, y: operator.sub(y, x)) _check_op(other, lambda x, y: operator.div(y, x)) _check_op(other, lambda x, y: operator.mul(y, x)) _check_op(other, lambda x, y: operator.pow(y, x))
def test_arithmetic_with_null(self): l, r = Scalar(1), Null() assert isinstance(l + r, Null) assert isinstance(l - r, Null) assert isinstance(l * r, Null) assert isinstance(l / r, Null) assert isinstance(l // r, Null) assert isinstance(l**r, Null) assert isinstance(l % r, Null) if not PY3: assert isinstance(operator.div(l, r), Null)
def p_expression_binop(p): """expression : expression PLUS expression | expression MINUS expression | expression TIMES expression | expression DIVIDE expression""" if p[2] == '+': p[0] = operator.add(p[1], p[3]) elif p[2] == '-': p[0] = operator.sub(p[1], p[3]) elif p[2] == '*': p[0] = operator.mul(p[1], p[3]) elif p[2] == '/': p[0] = operator.div(p[1], p[3])
def simulatedAnnealing(): print("SA") T = 100 listRuangan, listJadwal = readFile('Testcase.txt') current = createSpecies(listJadwal, listRuangan) neighbour = searchNeighbour(current, listRuangan) if (checkConstraint(current, listRuangan) >= checkConstraint( neighbour, listRuangan)): best = copySpecies(neighbour) current = copySpecies(neighbour) else: best = copySpecies(current) #mulai SA algorithm #Random Walk while (T > 0.0001) and (checkConstraint(best, listRuangan) != 0): neighbour = searchNeighbour(current, listRuangan) E = checkConstraint(current, listRuangan) Ei = checkConstraint(neighbour, listRuangan) if (E >= Ei): if (checkConstraint(best, listRuangan) >= checkConstraint( neighbour, listRuangan)): best = copySpecies(neighbour) current = copySpecies(neighbour) elif (T != 0): #kalo bad move p = probability(E, Ei, T) r = operator.div(100, p) if (r != 1): r = random.randrange(1, r) if (r == 1): current = copySpecies(neighbour) T = T - 0.01 #memulai Stochastic Hill Climbing if (checkConstraint(best, listRuangan) > 0): neighbour = SHC(best, listRuangan) while (checkConstraint(best, listRuangan) > (checkConstraint(neighbour, listRuangan))): best = copySpecies(neighbour) neighbour = SHC(best, listRuangan) for i in range(len(best)): best[i].print_jadwal() print 'Constraint broken: ' + str(checkConstraint(best, listRuangan)) constraint = checkConstraint(best, listRuangan) lcRuang, lcMatkul = getConstraint(best, listRuangan) totalRuang = 0 for i in range(len(listRuangan)): totalRuang += (listRuangan[i].jam_akhir - listRuangan[i].jam_mulai) * len(listRuangan[i].hari) return best, constraint, lcRuang, lcMatkul, totalRuang
def __div__(self, other): try: return Vector3(operator.div(self[0], other[0]), operator.div(self[1], other[1]), operator.div(self[2], other[2])) except TypeError: return Vector3(operator.div(self[0], other), operator.div(self[1], other), operator.div(self[2], other))