Ejemplo n.º 1
0
 def test_plus_minus(self):
     self.assertEqual(operator.sub(Q(3), 2), 1)
     self.assertEqual(Q(3) - 2, 1)
     self.assertEqual(Q(3) / 2, 1.5)
     self.assertEqual(3 / Q(2), 1.5)
     self.assertEqual(2 - Q(3), -1)
     self.assertEqual(operator.sub(2, Q(3)), -1)
Ejemplo n.º 2
0
def pr044(limit):
    pentagon = set(n*(3*n-1)//2 for n in range(1, limit))
    isPentagon = lambda x: x in pentagon
    cp = itertools.combinations(pentagon, 2)
    for x in cp:
        if isPentagon(add(*x)) and isPentagon(abs(sub(*x))):
            return abs(sub(*x))
    return "Not Found"
Ejemplo n.º 3
0
def quad(a,b,c):
    from cmath import sqrt
    if a!=0:
        z1=add((-b),sqrt(sub(b**2,4*a*c)))/(2*a)
        z2=sub((-b),sqrt(sub(b**2,4*a*c)))/(2*a)
        
    else:
        z1=z2(-c/b)
    return z1,z2
Ejemplo n.º 4
0
def slopeCalculation(pt1,pt2):
    dx2=operator.pow(operator.abs(operator.sub(pt1.X,pt2.X)),2)
    dy2=operator.pow(operator.abs(operator.sub(pt1.Y,pt2.Y)),2)
    dz2=operator.pow(operator.abs(operator.sub(pt1.Z,pt2.Z)),2)
    if dz2>0:
        vertical=operator.pow(dz2,0.5)
        horiz=operator.pow(dx2+dy2,0.5)
        slope=(vertical/horiz)*100
    else:
        slope=999
    return slope
Ejemplo n.º 5
0
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)
Ejemplo n.º 6
0
def a_plus_b(a,b):
	"""Return a+abs(b),but without calling abs.
	>>> a_plus_b(2,3)
	5
	>>>a_plus_b(2,-3)
	5
	"""
	if b < 0:
		sub(a,b)
	else:
		add(a,b)
Ejemplo n.º 7
0
def solution():
    # lol, if i don't use 'set', the time explode!
    # the most curious is the list already uniq!
    # p = pentagonal_list(3000); len(p) == len(set(p)) => True!!!
    # My guess is combinations had some optimizations for set
    # set type doesn't ordered too...

    pentagonals = set(pentagonal_list(3000))
    for c in combinations(pentagonals, 2):
        if add(*c) in pentagonals and abs(sub(*c)) in pentagonals:
            return abs(sub(*c))
Ejemplo n.º 8
0
 def test_subtraction(self, input_tuple, expected):
     self.ureg.autoconvert_offset_to_baseunit = False
     qin1, qin2 = input_tuple
     q1, q2 = self.Q_(*qin1), self.Q_(*qin2)
     input_tuple = q1, q2
     if expected == 'error':
         self.assertRaises(OffsetUnitCalculusError, op.sub, q1, q2)
     else:
         expected = self.Q_(*expected)
         self.assertEqual(op.sub(q1, q2).units, expected.units)
         self.assertQuantityAlmostEqual(op.sub(q1, q2), expected,
                                        atol=0.01)
Ejemplo n.º 9
0
def main():
    pentagonals = set(pentagonal(k) for k in range(1,3000))
    c = combinations(pentagonals,2)
    smallest = 10000000
    result = []
    for p in c:
        if add(*p) in pentagonals and abs(sub(*p)) in pentagonals:
            difference = abs(sub(*p))
            if difference < smallest:
                smallest = difference
                result = p
    print result
    print smallest
Ejemplo n.º 10
0
    def optimal_assignment(self, assignments):
        '''
        Given a set of possibly overlapping matches, find the
        optimal solution.
        '''
        diff_map = dict()
        for ids in assignments:
            diff_map[ids] = operator.sub(*assignments[ids])

        index_pair_sets = self.build_unique_index_pairs(assignments)

        def ordering_fn(index_pairs):
            total = 0
            for ix in index_pairs:
                total += max(assignments[ix])
            return total

        ordered_index_pairs_sets = sorted(index_pair_sets, key=ordering_fn, reverse=True)

        best_score = -float('inf')
        best_mapping = {}
        # prefer solutions which have a higher maximum value (more points of comparison)
        for assignment in ordered_index_pairs_sets:
            current_score = 0
            for ix in assignment:
                current_score += diff_map[ix]
            if current_score > best_score:
                best_score = current_score
                best_mapping = assignment
        return best_mapping
Ejemplo n.º 11
0
    def _alg_compare_hashes(self, method_name, dimension, cmp1, cmp2):
        if not method_name in self.hash_methods:
            return None
        method_info = self.hash_methods[method_name]
        difference_threshold = method_info['lims']
        try:
            if (type(cmp1) is str) or (type(cmp1) is unicode):
                cmp1 = method_info['obj'](cmp1)
            if (type(cmp2) is str) or (type(cmp2) is unicode):
                cmp2 = method_info['obj'](cmp2)
            diff = operator.sub(cmp1, cmp2)
            if diff is None:
                return None
            dist = method_info['dist'](diff, dimension)
        except:
            logging.warning('can not compare media hashes: ' + str(method_name))
            return None

        threshold = 0
        if dimension in difference_threshold:
            threshold = difference_threshold[dimension]
        else:
            test_dim = dimension - 1
            while test_dim >= 0:
                if test_dim in difference_threshold:
                    threshold = difference_threshold[test_dim]
                    break
                test_dim -= 1

        return {'diff': diff, 'dist': dist, 'similar': (diff <= threshold)}
Ejemplo n.º 12
0
def make_anonymous_factorial():
    """Return the value of an expression that computes factorial.

    >>> make_anonymous_factorial()(5)
    120
    """
    return lambda x: 1 if x <= 1 else mul(x, make_anonymous_factorial()(sub(x, 1)))
Ejemplo n.º 13
0
def nearest_date(month=1, day=1, offset=(2000, 1, 1)):
    offset = date(*offset)
    return min((
        date(offset.year, month, day),  # in current year
        date(add(offset.year, 1), month, day),  # in next year
        date(sub(offset.year, 1), month, day),  # in previous year
    ), key=lambda d: abs(_diff_dates(offset, d))).isoformat()
Ejemplo n.º 14
0
    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
Ejemplo n.º 15
0
def CalculateHashRounds(password, bonus):
    # Accepts a user password and bonus value, and calculates
    # the number of iterative rounds required. This function will
    # always return a value between 8 and 16,777,216.

    # Identify the number of Unicode characters.
    characters = len(password.decode("utf-8"))

    # Calculate the difficulty exponent by subtracting 1
    # for each Unicode character in a password.
    dynamic = operator.sub(24, characters)

    # Use a minimum exponent value of 1 for passwords
    # equal to, or greater than, 24 characters.
    dynamic = max(1, dynamic)

    # Derive the variable number of rounds based on the length.
    # Raise 2 using the dynamic exponent determined above.
    variable = pow(2, dynamic)

    # If applicable, add the fixed number of bonus rounds.
    total = operator.add(variable, bonus)

    # If the value of rounds is smaller than 8, reset
    # the value to 8.
    total = max(8, total)

    # If the value of rounds is larger than 16,777,216, reset
    # the value to 16,777,216.
    total = min(pow(2, 24), total)

    return total
Ejemplo n.º 16
0
    def p_expression_binop(self, p):
        """expression : expression PLUS expression
                      | expression MINUS expression
                      | expression TIMES expression
                      | expression DIVIDE expression
                      | expression MODULUS expression
                      | expression EXPONENT expression"""

        op = p[2]
        left = self._sumDiceRolls(p[1])
        right = self._sumDiceRolls(p[3])

        if op == '+':
            p[0] = operator.add(left, right)
        elif op == '-':
            p[0] = operator.sub(left, right)
        elif op == '*':
            p[0] = operator.mul(left, right)
        elif op == '/':
            p[0] = operator.floordiv(left, right)
        elif op == '%':
            p[0] = operator.mod(left, right)
        elif op == '^':
            if -self._MAX_EXPONENT <= left <= self._MAX_EXPONENT and -self._MAX_EXPONENT <= right <= self._MAX_EXPONENT:
                p[0] = operator.pow(left, right)
            else:
                raise InvalidOperandsException(u'operand or exponent is larger than the maximum {}'
                                               .format(self._MAX_EXPONENT))
Ejemplo n.º 17
0
 def __init__(self, mobject, tracked_mobject, **kwargs):
     self.tracked_mobject = tracked_mobject
     self.diff = op.sub(
         mobject.get_center(),
         tracked_mobject.get_center(),
     )
     super().__init__(mobject, **kwargs)
Ejemplo n.º 18
0
Archivo: util.py Proyecto: whilp/tsar
def adiff(seq, points=5, fxns={}):
    """Generate approximate values for the first derivative of *seq*.

    *seq* is a sequence of (x, y) tuples, where x increases at a constant rate. 
    *points* is an integer indicating the number of neighbor points to consider 
    when approximating f`(x). *fxns* is a dictionary mapping the number of
    points to a function that, given the list of neighboring f(x) values centered
    at x, calculates f`(x).
    """
    h = None
    ys = range(points)
    xs = list(ys)

    for i, coord in enumerate(seq):
        loc = i % points
        xs[loc], ys[loc] = coord

        if i == 1:
            h = abs(operator.sub(*xs[:2]))

        if i >= points:
            center = (i - (points/2)) % points
            x = xs[center]
            y = ys[center:] + ys[:center]
            try:
                yield (x, fxns[points](y, h))
            except TypeError:
                yield (x, None)
Ejemplo n.º 19
0
 def test_result(self):
     types = np.typecodes['AllInteger'] + np.typecodes['AllFloat']
     with suppress_warnings() as sup:
         sup.filter(RuntimeWarning)
         for dt in types:
             a = np.ones((), dtype=dt)[()]
             assert_equal(operator.sub(a, a), 0)
Ejemplo n.º 20
0
def index_view(request):
    print(request.POST)
    try:
        if request.POST:
            first_number_input = float(request.POST['first_number_input'])
            second_number_input = float(request.POST['second_number_input'])
            operation = request.POST["operator"]

            if operation == "+ (add)":
                answer = operator.add(first_number_input, second_number_input)
                operation = "+"
            elif operation == "- (subtract)":
                answer = operator.sub(first_number_input, second_number_input)
                operation = "-"
            elif operation == "x (multiply)":
                answer = operator.mul(first_number_input, second_number_input)
                operation = "x"
            else:
                try:
                    answer = operator.truediv(first_number_input, second_number_input)
                except ZeroDivisionError:
                    answer = "Answer is Undefined (You can't divide by zero)"
                operation = "/"
            return render(request, 'index.html', {'answer': answer,
                                                  'operation': operation,
                                                  'first_number': first_number_input,
                                                  'second_number': second_number_input})
        else:
            return render(request,'index.html',{})
    except (ValueError, TypeError):
        answer = "INVALID ENTRY"
        return render(request, "index.html",{'answer':answer})
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
Ejemplo n.º 22
0
    def read(self):
        assert self.fpath != ''
        raw_df = pan.read_csv(self.fpath, header=None, names=self._raw_names,
                parse_dates=[self.DTIM], index_col=self.DTIM)

        vidn_ser = raw_df[self.FNAM].apply(lambda x: x[0:4])
        dtms = raw_df.index.values#[self.DTIM].apply(lambda x: dt.datetime.strptime(x,
            #self.timef)).values
        
        iats = [op.sub(*l).item()/1.0e+9 for l in zip(dtms[1:], 
            dtms[0:len(dtms)]) ]
        iats = [1.] + iats
        iats_ser = pan.Series(iats, index=raw_df.index)
        iats_ser.name = self.IATS
        
        arate =  round(len(iats)/sum(iats))
        arate_ser = pan.Series(np.full(len(iats), arate), index=raw_df.index)
        arate_ser.name = self.ARAT

        trsz_log10_ser = np.log10(raw_df[co.CN_TRSZ])
        trsz_log10_ser.name = co.CN_TRSZLOG10

        self.log = pan.concat([
            vidn_ser, 
            iats_ser, 
            arate_ser, 
            trsz_log10_ser,
            raw_df[self.TRSZ],
            raw_df[self.WAIT],
            raw_df[self.DLTM]], axis=1)
Ejemplo n.º 23
0
def make_anonymous_factorial():
    """Return the value of an expression that computes factorial.

    >>> make_anonymous_factorial()(5)
    120
    """
    return (lambda f: lambda k: f(f, k))(lambda f, k: k if k == 1 else mul(k, f(f, sub(k, 1))))
Ejemplo n.º 24
0
Archivo: Geom.py Proyecto: oserve/PyNMR
def calcDistance(*coords):
    """    Calculate distance according to :
    ((sum of all distances^-6)/number of distances)^-1/6
    or (sum of all distances^-6)^-1/6

    calcDistance.method should be set before use
    """
    result = None

    try:
        distance_list = (sqrt(fsum(sub(*coord) ** 2 for coord in izip(*atoms))) for atoms in product(*coords))
        sum6 = fsum(pow(distance, -6) for distance in distance_list)
        if calcDistance.method == 'ave6':
            number_of_distances = reduce(mul, (len(coord) for coord in coords))
        elif calcDistance.method == 'sum6':
            number_of_distances = 1
        result = pow(sum6/number_of_distances, -1./6)
    except(ValueError, TypeError):
        errors.add_error_message("Problem using coordinates : " +
                                 str(coords) + "\n" +
                                 " and distances list : " +
                                 str([distance for distance in distance_list]) + "\n")
    except AttributeError:
        sys.stderr.write("Please set calcDistance.method before using calcDistance()\n")

    return result
Ejemplo n.º 25
0
def ch_to_op(c, x, y):

    if c == '+':
        return operator.add(x, y)
    elif c == '-':
        return operator.sub(x, y)
    elif c == 'x':
        return operator.mul(x, y)
Ejemplo n.º 26
0
 def test_memo_independence(self):
     from operator import add, sub
     madd = memo(add)
     msub = memo(sub)
     for a in range(10):
         for b in range(10):
             self.assertEqual(madd(a,b), add(a,b))
             self.assertEqual(msub(a,b), sub(a,b))
Ejemplo n.º 27
0
 def do_it(self):
     if self.op == 'add':
         self.result = operator.add(self.first, self.second)
     elif self.op == 'subtract':
         self.result = operator.sub(self.first, self.second)
     
     print('{0} {1} {2} = {3}'.format(self.first, self.op, self.second, self.result))
     pv.update()
Ejemplo n.º 28
0
def _is_true_neighbor(
        x, attractor_radius, offset, indices, distance,
        relative_distance_cutoff=15,
        relative_radius_cutoff=2
):
    distance_increase = np.abs(sub(*x[indices + offset]))
    return (distance_increase / distance < relative_distance_cutoff and
            distance_increase / attractor_radius < relative_radius_cutoff)
Ejemplo n.º 29
0
 def leaf_pixelsep(self):
     y0, y1 = self.get_ylim()
     y0 = max(0, y0); y1 = min(1, y1)
     display_points = self.transData.transform(((0, y0), (0, y1)))
     # height in pixels (visible y data extent)
     height = operator.sub(*reversed(display_points[:,1]))
     pixelsep = height/((y1-y0)/self.leaf_hsep)
     return pixelsep
def match(wild_type, data_1):
    d = {}
    import ipdb; ipdb.set_trace()
    for i in wild_type:
        match = re.search('{}'.format(i),data_1)
        if match:
            i,j = match.span()
            d.setdefault(i,[]).append(j)
    return max(((i,j[-1]) for i,j in d.items()),key=lambda x:abs(sub(*x)))
Ejemplo n.º 31
0
def modelF():
    G_data = Gen_Data()
    s0 = G_data.Generate_Int(2, 20)
    s1 = G_data.Generate_Int(2, 20)
    s2 = operator.mul(s0, s1)
    x = "X"
    op1 = G_data.opSub
    op2 = G_data.opDiv
    s3 = G_data.Generate_Int(s2, 1000)
    result_ = operator.sub(s3, s2)
    result = "( %d %s %s ) %s %d = %d" % (s3, op1, x, op2, s1, s0)
    return result, result_
Ejemplo n.º 32
0
def cost_AS(action, posBox):

    cost = len([x for x in action if x.islower()])

    from operator import sub, add

    posBox = [add(x, y) for x, y in sorted(posBox)]
    posGoal = [add(x, y) for x, y in sorted(posGoals)]

    distance = sum([abs(sub(x, y)) for x, y in zip(posBox, posGoal)])

    return cost + distance
Ejemplo n.º 33
0
def make_anonymous_factorial():
    """Return the value of an expression that computes factorial.

    >>> make_anonymous_factorial()(5)
    120
    >>> from construct_check import check
    >>> check(HW_SOURCE_FILE, 'make_anonymous_factorial', ['Assign', 'AugAssign', 'FunctionDef', 'Recursion'])
    True
    """
    # I can't figure it out, this is other's solution.
    return (lambda f: lambda k: f(f, k)
            )(lambda f, k: 1 if k == 1 else mul(k, f(f, sub(k, 1))))
Ejemplo n.º 34
0
 def begin(self):
     super().begin()
     car = self.mobject
     distance = get_norm(
         op.sub(
             self.target_mobject.get_right(),
             self.starting_mobject.get_right(),
         ))
     if not self.moving_forward:
         distance *= -1
     tire_radius = car.get_tires()[0].get_width() / 2
     self.total_tire_radians = -distance / tire_radius
Ejemplo n.º 35
0
def make_anonymous_factorial():
    """Return the value of an expression that computes factorial.

    >>> make_anonymous_factorial()(5)
    120
    >>> from construct_check import check
    >>> check(HW_SOURCE_FILE, 'make_anonymous_factorial', ['Assign',\
         'AugAssign', 'FunctionDef', 'Recursion'])
    True
    """
    return lambda n: (lambda f, v: f(f, v))(lambda f, v: 1 if v == 1 else mul(
        v, f(f, sub(v, 1))), n)
Ejemplo n.º 36
0
        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))
Ejemplo n.º 37
0
 def process(self):
     switcher = {
         Operator.PLUS:
         operator.add(self.input1.process(), self.input2.process()),
         Operator.MINUS:
         operator.sub(self.input1.process(), self.input2.process()),
         Operator.MULT:
         operator.mul(self.input1.process(), self.input2.process()),
         Operator.DIV:
         operator.truediv(self.input1.process(), self.input2.process())
     }
     return switcher.get(self.operator)
Ejemplo n.º 38
0
def a_plus_abs_b(a, b):
    """Return a+abs(b), but without calling abs.

    >>> a_plus_abs_b(2, 3)
    5
    >>> a_plus_abs_b(2, -3)
    5
    """
    if b < 0:
        return sub(a,b)
    else:
        return add(a,b)
Ejemplo n.º 39
0
def modelC():
    G_data = Gen_Data()
    flag = True
    s0 = G_data.Generate_Decimal(10.00, 20.00, 2)
    x = "X"
    op = G_data.opSub
    s1 = G_data.Generate_Int(2, 20)
    s2 = G_data.Generate_Decimal(1.00, 20.00, 2)
    s3 = operator.mul(s1, s0)
    s3 = operator.sub(s3, s2)
    result = "%d %s %s %.2f = %.2f" % (s1, x, op, s2, s3)
    return result, float(s0)
Ejemplo n.º 40
0
def make_anonymous_factorial():
    """Return the value of an expression that computes factorial.

    >>> make_anonymous_factorial()(5)
    120
    >>> from construct_check import check
    >>> # ban any assignments or recursion
    >>> check(HW_SOURCE_FILE, 'make_anonymous_factorial', ['Assign', 'AugAssign', 'FunctionDef', 'Recursion'])
    True
    """
    return (lambda f: lambda k: f(f, k)
            )(lambda f, k: k if k == 1 else mul(k, f(f, sub(k, 1))))
Ejemplo n.º 41
0
        def check(a, b):
            _check_op(a, b, operator.add)
            _check_op(a, b, operator.sub)
            _check_op(a, b, operator.truediv)
            _check_op(a, b, operator.floordiv)
            _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.truediv(y, x))
            _check_op(a, b, lambda x, y: operator.floordiv(y, x))
            _check_op(a, b, lambda x, y: operator.mul(y, x))
Ejemplo n.º 42
0
def get_question_answer():
    num1, operation, num2 = get_expression()
    question = '{} {} {}'.format(num1, operation, num2)
    if operation == '+':
        answer = str(operator.add(num1, num2))
        return question, answer
    elif operation == '-':
        answer = str(operator.sub(num1, num2))
        return question, answer
    elif operation == '*':
        answer = str(operator.mul(num1, num2))
        return question, answer
Ejemplo n.º 43
0
def make_anonymous_factorial():
    """Return the value of an expression that computes factorial.

    >>> make_anonymous_factorial()(5)
    120
    >>> from construct_check import check
    >>> # ban any assignments or recursion
    >>> check(HW_SOURCE_FILE, 'make_anonymous_factorial', ['Assign', 'AugAssign', 'FunctionDef', 'Recursion'])
    True
    """
    return (lambda n: (lambda fact: fact(n, fact))
            (lambda n, fact: 1 if n == 1 else mul(n, fact(sub(n, 1), fact))))
Ejemplo n.º 44
0
def generate_data():
    a = random.randint(1, 100)
    b = random.randint(1, 100)
    operation = random.choice(['+', '-', '*'])
    if operation == '*':
        right_answer = operator.mul(a, b)
    if operation == '+':
        right_answer = operator.add(a, b)
    if operation == '-':
        right_answer = operator.sub(a, b)
    question = str(a) + ' ' + operation + ' ' + str(b)
    return question, str(right_answer)
Ejemplo n.º 45
0
def _is_true_neighbor(x,
                      attractor_radius,
                      offset,
                      indices,
                      distance,
                      relative_distance_cutoff=15,
                      relative_radius_cutoff=2):
    # Created by hsharrison
    # pypsr taken from https://github.com/hsharrison/pypsr MIT License
    distance_increase = np.abs(sub(*x[indices + offset]))
    return (distance_increase / distance < relative_distance_cutoff
            and distance_increase / attractor_radius < relative_radius_cutoff)
Ejemplo n.º 46
0
def modelG():
    G_data = Gen_Data()
    s0 = G_data.Generate_Int(2, 30)
    s1 = G_data.Generate_Int(2, 30)
    s2 = operator.mul(s0, s1)
    x = "X"
    op1 = G_data.opAdd
    op2 = G_data.opDiv
    s3 = G_data.Generate_Int(2, s1)
    result_ = operator.sub(s1, s3)
    result = "%d %s ( %s %s %d ) = %d" % (s2, op2, x, op1, s3, s0)
    return result, result_
Ejemplo n.º 47
0
 def __sub__(self, other: object) -> Union['DayTimeDuration', 'Time']:
     if isinstance(other, self.__class__):
         delta = operator.sub(*self._get_operands(other))
         return DayTimeDuration.fromtimedelta(delta)
     elif isinstance(other, DayTimeDuration):
         dt = self._dt - other.get_timedelta()
         return Time(dt.hour, dt.minute, dt.second, dt.microsecond, dt.tzinfo)
     elif isinstance(other, datetime.timedelta):
         dt = self._dt - other
         return Time(dt.hour, dt.minute, dt.second, dt.microsecond, dt.tzinfo)
     else:
         raise TypeError("wrong type %r for operand %r" % (type(other), other))
Ejemplo n.º 48
0
def modelI():
    G_data = Gen_Data()
    s0 = G_data.Generate_Int(2, 30)
    s1 = G_data.Generate_Int(50, 100)
    s2 = G_data.Generate_Int(2, s1)
    s3 = operator.sub(s1, s2)
    x = "X"
    op1 = G_data.opDiv
    op2 = G_data.opSub
    result_ = operator.mul(s0, s1)
    result = "%s %s %d %s %d = %d" % (x, op1, s0, op2, s2, s3)
    return result, result_
Ejemplo n.º 49
0
    def _test_quantity_iadd_isub(self, unit, func):
        x = self.Q_(unit, "centimeter")
        y = self.Q_(unit, "inch")
        z = self.Q_(unit, "second")
        a = self.Q_(unit, None)

        func(op.iadd, x, x, self.Q_(unit + unit, "centimeter"))
        func(
            op.iadd,
            x,
            y,
            self.Q_(unit + self.NON_INT_TYPE("2.54") * unit, "centimeter"),
        )
        func(op.iadd, y, x,
             self.Q_(unit + unit / self.NON_INT_TYPE("2.54"), "inch"))
        func(op.iadd, a, unit, self.Q_(unit + unit, None))
        with pytest.raises(DimensionalityError):
            op.iadd(self.NON_INT_TYPE("10"), x)
        with pytest.raises(DimensionalityError):
            op.iadd(x, self.NON_INT_TYPE("10"))
        with pytest.raises(DimensionalityError):
            op.iadd(x, z)

        func(op.isub, x, x, self.Q_(unit - unit, "centimeter"))
        func(op.isub, x, y,
             self.Q_(unit - self.NON_INT_TYPE("2.54"), "centimeter"))
        func(op.isub, y, x,
             self.Q_(unit - unit / self.NON_INT_TYPE("2.54"), "inch"))
        func(op.isub, a, unit, self.Q_(unit - unit, None))
        with pytest.raises(DimensionalityError):
            op.sub(self.NON_INT_TYPE("10"), x)
        with pytest.raises(DimensionalityError):
            op.sub(x, self.NON_INT_TYPE("10"))
        with pytest.raises(DimensionalityError):
            op.sub(x, z)
Ejemplo n.º 50
0
def parse_parameter(parameter: Parameter):
    if parameter.kind == "topic":
        topic = get_topic_by_id(parameter.topicId)
        topic_col_name = build_collection_name(topic.name)
        factor = get_factor(parameter.factorId, topic)
        return Table(topic_col_name)[factor.name]
    elif parameter.kind == 'constant':
        return parameter.value
    elif parameter.kind == 'computed':
        if parameter.type == Operator.add:
            result = None
            for item in parameter.parameters:
                if result:
                    result = operator.add(result, parse_parameter(item))
                else:
                    result = parse_parameter(item)
            return result
        elif parameter.type == Operator.subtract:
            result = None
            for item in parameter.parameters:
                if result:
                    result = operator.sub(result, parse_parameter(item))
                else:
                    result = parse_parameter(item)
            return result
        elif parameter.type == Operator.multiply:
            result = None
            for item in parameter.parameters:
                if result:
                    result = operator.mul(result, parse_parameter(item))
                else:
                    result = parse_parameter(item)
            return result
        elif parameter.type == Operator.divide:
            result = None
            for item in parameter.parameters:
                if result:
                    result = operator.truediv(result, parse_parameter(item))
                else:
                    result = parse_parameter(item)
            return result
        elif parameter.type == Operator.modulus:
            result = None
            for item in parameter.parameters:
                if result:
                    result = operator.mod(result, parse_parameter(item))
                else:
                    result = parse_parameter(item)
            return result
        else:
            # TODO more operator support
            raise Exception("operator is not supported")
Ejemplo n.º 51
0
    def do_it(self):
        if self.op == 'add':
            res = operator.add(self.first, self.second)
        elif self.op == 'subtract':
            res = operator.sub(self.first, self.second)

        self.count += 1
        self.ind.append(self.count)
        self.result.append(res)

        print('{0} {1} {2} = {3}'.format(self.first, self.op, self.second,
                                         res))
        pv.update()
Ejemplo n.º 52
0
 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])
Ejemplo n.º 53
0
def test_predict__english__random(english):
    test = tuple(
        "".join(
            random.choice([" "] + list(string.ascii_letters))
            for _ in range(random.randint(5, 50))
        )
        for _ in range(10)
    )
    predict = create_model(*english)
    result = [1 - min(1, exp(-sub(*predict(t)))) for t in test]

    for r in result:
        assert r < 0.95
Ejemplo n.º 54
0
def minus(exps, env) :
	'(- 1 2) OR (- 1)'
	nums = tuple(eval_params(exps, env))
	if len(nums) == 1 :
		a, = nums
		assert type(a) == Number
		return operator.neg(a)
	elif len(nums) == 2 :
		a, b = nums
		assert type(a) == Number and type(b) == Number
		return operator.sub(a, b)
	else :
		raise Exception('Invalid variable numbers for - function')
Ejemplo n.º 55
0
def make_anonymous_factorial():
    """Return the value of an expression that computes factorial.

    # >>> make_anonymous_factorial()(5)
    120
    # # >>> from construct_check import check
    # >>> check(HW_SOURCE_FILE, 'make_anonymous_factorial', ['Assign', 'AugAssign', 'FunctionDef', 'Recursion'])
    True
    """
    # def f(n):
    #     if n == 1: return 1
    #     return mul(n, f(sub(n,1)))
    return (lambda a: lambda v: a(a, v))(lambda s, x: 1 if x == 0 else mul(x, s(s, sub(x, 1))))
Ejemplo n.º 56
0
def a_plus_abs_b(a, b):
    """Return a+abs(b), but without calling abs.

    >>> a_plus_abs_b(2, 3)
    5
    >>> a_plus_abs_b(2, -3)
    5
    """
    if b < 0:
        f = lambda x, y: sub(x, y)
    else:
        f = lambda x, y: add(x, y)
    return f(a, b)
Ejemplo n.º 57
0
def make_anonymous_factorial():
    """Return the value of an expression that computes factorial.

    >>> make_anonymous_factorial()(5)
    120
    >>> from construct_check import check
    >>> check(HW_SOURCE_FILE, 'make_anonymous_factorial', ['Assign', 'AugAssign', 'FunctionDef', 'Recursion'])
    True
    """


    # 函数 refer 的name就在lambda上作为参数
    return (lambda f: lambda n: f(f, n))   (lambda f, n: 1 if n==1 else mul(n, f(f, sub(n, 1))))
Ejemplo n.º 58
0
def make_anonymous_factorial():
    """Return the value of an expression that computes factorial.

    >>> make_anonymous_factorial()(5)
    120
    >>> from construct_check import check
    >>> # ban any assignments or recursion
    >>> check(HW_SOURCE_FILE, 'make_anonymous_factorial', ['Assign', 'AugAssign', 'FunctionDef', 'Recursion'])
    True
    """
    # return lambda n: (lambda f, index, res: res if index == 1 else f(f, sub(index, 1), mul(res, index)))(, n, 1)
    return lambda n: (lambda f1, index1, res1: f1(f1, index1, res1)) \
        (lambda f2, index2, res2: res2 if index2 == 1 else f2(f2, sub(index2, 1), mul(res2, index2)), n, 1)
Ejemplo n.º 59
0
def a_plus_abs_b(a, b):
    """Return a+abs(b), but without calling abs.

    >>> a_plus_abs_b(2, 3)
    5
    >>> a_plus_abs_b(2, -3)
    5
    """
    if b < 0:
        f = lambda a, b: add(a, sub(0, b))
    else:
        f = lambda a, b: add(a, b)
    return f(a, b)
Ejemplo n.º 60
0
def make_anonymous_factorial():
    """Return the value of an expression that computes factorial.

    >>> make_anonymous_factorial()(5)
    120
    >>> from construct_check import check
    >>> # ban any assignments or recursion
    >>> check(HW_SOURCE_FILE, 'make_anonymous_factorial', ['Assign', 'AugAssign', 'FunctionDef', 'Recursion'])
    True
    """
    # return (lambda f: lambda n: 1 if n == 1 else mul(n, f(f)(sub(n, 1))))(lambda f: lambda n: 1 if n == 1 else mul(n, f(f)(sub(n, 1))))
    return (lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
            )(lambda f: lambda n: (1 if n < 2 else mul(n, f(sub(n, 1)))))