Example #1
0
 def __add__(self, right):
     Fraction._validate_arithmetic(right, {Fraction, int}, '+',
                                   type_as_str(self), type_as_str(right))
     if type(right) == int:
         right = Fraction(right)
     return Fraction((self.num * right.denom) + (self.denom * right.num),
                     self.denom * right.denom)
Example #2
0
 def __delitem__(self,index):
     if type(index) != int:
         raise TypeError('Index must be type int. Type {} given.'.format(type_as_str(type(index))))
     if index < 0:
         raise TypeError('Index must be greater than 0. {} < 0.'.format(type_as_str(index)))
     if index in self.terms.keys():
         del self.terms[index]
Example #3
0
 def __init__(self, x, y):
     assert type(x) is int, 'Point.__init__: x(' + str(
         x) + ') is not an int(' + type_as_str(x) + ')'
     assert type(y) is int, 'Point.__init__: y(' + str(
         y) + ') is not an int(' + type_as_str(y) + ')'
     self.x = x
     self.y = y
    def __mul__(self, right):
        if type(right) not in [int, float, Sparse_Matrix]:
            raise TypeError('unsupported operand type(s) for +' + ': \'' +
                            type_as_str(self) + '\' and \'' +
                            type_as_str(right) + '\'')
        if type(self) is Sparse_Matrix and type(right) is Sparse_Matrix:
            if self.cols != right.rows:
                raise AssertionError("Size of two Sparse_Matrix are not equal")
            nm = Sparse_Matrix(self.rows, right.cols)
            for index in range(self.rows):
                for indexs in range(right.cols):
                    num = self.row(index)
                    nums = right.col(indexs)
                    xs = 0
                    xy = None
                    if len(num) > len(nums):
                        xy = num
                    else:
                        xy = nums
                    for x in range(len(xy)):
                        xs += num[x] * nums[x]
                    nm[index, indexs] = xs
            return nm

        if type(right) in [int, float]:
            nm = Sparse_Matrix(self.rows, self.cols)
            for index in range(self.rows):
                for indexs in range(self.cols):
                    fr = self.matrix.get((index, indexs), 0) * right
                    nm[index, indexs] = fr
            return nm
Example #5
0
 def __gt__(self, right):
     Fraction._validate_relational(right, {Fraction, int}, '>',
                                   type_as_str(right))
     if type_as_str(right) == "int":
         return self.num > self.denom * right
     elif type_as_str(right) == "fraction.Fraction":
         return self.num * right.denom > right.num * self.denom
Example #6
0
 def __rmul__(self, left):
     Fraction._validate_arithmetic(left, {Fraction, int}, '*',
                                   type_as_str(left), 'Fraction')
     if type_as_str(left) == "int":
         return Fraction(self.num * left, self.denom)
     elif type_as_str(left) == "fraction.Fraction":
         return Fraction(self.num * left.num, self.denom * left.denom)
 def error_message():
     if type(annot) is type:
         return "AssertionError: " + repr(param) + " failed annotation check(wrong type): value = " + repr(value[param]) + \
                "\n   was type " + type_as_str(value[param]) + " ...should be type " + str(annot.__name__) + "\n" + ''.join(check_history_list)
     else:
         return "AssertionError: " + repr(param) + " failed annotation check(wrong type): value = " + repr(value[param]) + \
                "\n   was type " + type_as_str(value[param]) + " ...should be type " + str(type(annot).__name__) + "\n" + ''.join(check_history_list)
Example #8
0
 def __mul__(self, right):
     Fraction._validate_arithmetic(right, {Fraction, int}, '*', 'Fraction',
                                   type_as_str(right))
     if type_as_str(right) == "int":
         return Fraction(self.num * right, self.denom)
     elif type_as_str(right) == "fraction.Fraction":
         return Fraction(self.num * right.num, self.denom * right.denom)
Example #9
0
 def __radd__(self,left):
     
     answer = Poly()
     
     if 'Poly' not in type_as_str(self) or type_as_str(left) not in ['int', 'float']\
      and 'Poly' not in type_as_str(left):
         
         raise TypeError('Operands must be of type Poly and Poly or int or float')
     
     elif 'Poly' in type_as_str(self) and 'Poly' in type_as_str(left):
         for power in self.terms:
             answer._add_term(self.terms[power], power)
         for power in left.terms:
             if power in answer.terms:
                 answer.terms[power] += left.terms[power]
             else:
                 answer._add_term(left.terms[power], power)
                 
     else:
         for power in self.terms:
             answer._add_term(self.terms[power], power)
         
         if 0 in answer.terms:
             answer.terms[0] += left
         else:
             answer._add_term(left,0)
             
     return answer
 def __gt__(self,right):
     if type(right) == DictList:
         return set(self.items()) > set(DictList.items(right))
     elif type(right) == dict:
         return set(self.items()) > set((x,y) for x,y in right.items())
     else:
         raise TypeError("unorderable types: " +type_as_str(self)+"() and "+type_as_str(right)+"()")            
Example #11
0
 def _validate_addsub(l,r,op):
     Dimensional._validate_relational(l,r,op)
     if type(l) in [int,float] and r['d'] != (0,0,0):
         raise DimensionError('incompatible dimensions for '+op+
                         ': \''+type_as_str(l)+'\' and \''+str(r['d'])+'\'')        
     if type(r) in [int,float] and l['d'] != (0,0,0):
         raise DimensionError('incompatible dimensions for '+op+
                         ': \''+str(l['d'])+'\' and \''+type_as_str(r)+'\'')        
Example #12
0
 def __add__(self, right):
     if type(right) != type(self):
         raise TypeError('unsupported operand type(s) for +' + ': \'' +
                         type_as_str(self) + '\' and \'' +
                         type_as_str(right) + '\'')
     new_coords = [(x + y)
                   for x, y in zip(self.coordinates, right.coordinates)]
     return Point(new_coords[0], new_coords[1], new_coords[2])
Example #13
0
 def __add__(self, right):
     n_list = []
     if type(right) is not Bag:
         raise TypeError('unsupported operand type(s) for +' + ': \'' +
                         type_as_str(self) + '\' and \'' +
                         type_as_str(right) + '\'')
     n_list.extend(self.__item_list)
     n_list.extend(right.__item_list)
     return Bag(n_list)
Example #14
0
 def check_list(type_item):
     assert isinstance(value, type_item),error_message(error = 'incorrect type')
     if len(annot) == 1:
         for i in range(len(value)):
             self.check(param, annot[0], value[i], check_history + '\n' + type_as_str((annot)) + str([i]) + 'check: '+str(annot[0]))
     elif len(annot) > 1:
         assert len(annot) == len(value), error_message( error = 'wrong number')
         for i in range(len(annot)):
             self.check(param, annot[i], value[i], check_history + '\n' + type_as_str((annot)) + str([i]) + 'check: '+str(annot[i]))
Example #15
0
 def __rtruediv__(self, left):
     Fraction._validate_arithmetic(left, {Fraction, int}, '/',
                                   type_as_str(left), 'Fraction')
     if type_as_str(left) == "int":
         if left == 0:
             raise ZeroDivisionError
         return Fraction(self.denom * left, self.num)
     elif type_as_str(left) == "fraction.Fraction":
         return Fraction(self.denom * left.num, self.num * left.denom)
Example #16
0
 def __truediv__(self, right):
     Fraction._validate_arithmetic(right, {Fraction, int}, '/', 'Fraction',
                                   type_as_str(right))
     if type_as_str(right) == "int":
         if right == 0:
             raise ZeroDivisionError
         return Fraction(self.num, self.denom * right)
     elif type_as_str(right) == "fraction.Fraction":
         return Fraction(self.num * right.denom, self.denom * right.num)
Example #17
0
 def __pow__(self,right):
     if type(right) is not int:
         raise TypeError('unsupported operand type(s) for **'+
                         ': \''+type_as_str(self)+'\' and \''+type_as_str(right)+'\'')        
     mult = (self if right >= 0 else 1/self)
     answer = Interval(1.,1.)
     for _ in range(abs(right)):
         answer *= mult
     return answer
Example #18
0
 def _validate_addsub(l, r, op):
     Dimensional._validate_relational(l, r, op)
     if type(l) in [int, float] and r['d'] != (0, 0, 0):
         raise DimensionError('incompatible dimensions for ' + op + ': \'' +
                              type_as_str(l) + '\' and \'' + str(r['d']) +
                              '\'')
     if type(r) in [int, float] and l['d'] != (0, 0, 0):
         raise DimensionError('incompatible dimensions for ' + op + ': \'' +
                              str(l['d']) + '\' and \'' + type_as_str(r) +
                              '\'')
Example #19
0
 def __call__(self,arg):
     num = 0
     if type_as_str(arg) != 'int' and type_as_str(arg) != 'float':
         raise TypeError
     else:
         for i in self.terms.keys():
             newnum = arg**i
             newnum = newnum * self.terms[i]
             num += newnum
     return num
Example #20
0
File: bag.py Project: walg/database
 def _validate_bags(self, right, op):
     if type(right) is not Bag:
         raise TypeError(
             "unsupported operand type(s) for "
             + op
             + ": '"
             + type_as_str(self)
             + "' and '"
             + type_as_str(right)
             + "'"
         )
Example #21
0
 def correct(self,tuples):
     if type_as_str(tuples[0]) != 'int' and type_as_str(tuples[0]) != 'float':
         raise AssertionError('Poly.__init__: illegal Coeff in ' + str(tuples))
     elif type_as_str(tuples[1]) != 'int':
         raise AssertionError('Poly.__init__: illegal power in ' + str(tuples))
     elif (int(tuples[1]) < 0):
         raise AssertionError('Poly.__init__: illegal power in ' + str(tuples))
     else:
         if tuples[0] == 0:
             return False
         return True
Example #22
0
 def check_sequence(kind, kind_text):
     assert isinstance(value, kind), 'Wrong whole type: ' + type_as_str(value) + '... should be ' + kind_text
     
     if len(annot) == 1:
         i = 0
         for v in value:
             self.check(param,annot[0],v,check_history+kind_text+'['+str(i)+'] check: '+str(annot[0])+'\n')
             i += 1
     else:
         assert len(annot) == len(value), 'Different length of value and annot!'
         for v,k in zip(value, annot):
             assert isinstance(v, k), 'Wrong single type: ' + type_as_str(v) + '... should be ' + str(k)
 def __rsub__(self, left):
     if type(left) not in [int, float, Sparse_Matrix]:
         raise TypeError('unsupported operand type(s) for +' + ': \'' +
                         type_as_str(self) + '\' and \'' +
                         type_as_str(left) + '\'')
     if type(left) in [int, float]:
         nm = Sparse_Matrix(self.rows, self.cols)
         for index in range(self.rows):
             for indexs in range(self.cols):
                 fr = self.matrix.get((index, indexs), 0) - left
                 nm[index, indexs] = fr
         return nm
 def check_list_tup(t):
     assert isinstance(value,t), repr(param)+" failed annotation check(wrong type): value = "+repr(value)+\
     "\n  was type "+type_as_str(value)+" ...should be type "+str(t)+"\n"+check_history
     
     if len(annot) == 1:
         for v in value:
             self.check(param, annot[0], v, check_history+type_as_str(value)+"["+str(value.index(v))+"] check: "+str(annot[0])+"\n")
     else:
         assert len(annot) == len(value), repr(param)+" failed annotation check(wrong number of elements): value = "+repr(value)+\
         "\n  annotation had "+str(len(annot))+" elements"+str(annot)+"\n"+check_history
         for a,v in zip(annot,value):
             self.check(param, a, v, check_history+type_as_str(value)+"["+str(value.index(v))+"] check: "+str(annot.index(a))+"\n")
Example #25
0
 def __gt__(self, right):
     keys_self = self._all_keys()
     if type(right) is DictList:
         keys_right = right._all_keys()
     elif type(right) is dict:
         keys_right = {k for k in right}
     else:
         raise TypeError('DictList.__gt__: incompatible type for left(' +
                         type_as_str(self) + ') and right(' +
                         type_as_str(right) + ')')
     return keys_self > keys_right and all(
         (self[a] == right[a] for a in keys_right))
Example #26
0
 def __lt__(self, right):
     if type(right) in (int, float):
         return math.sqrt(sum([value**2
                               for value in self.coordinates])) < right
     elif type(right) is type(self):
         return math.sqrt(sum(
             [value**2 for value in self.coordinates])) < math.sqrt(
                 sum([value**2 for value in right.coordinates]))
     else:
         raise TypeError('unsupported operand type(s) for <' + ': \'' +
                         type_as_str(self) + '\' and \'' +
                         type_as_str(right) + '\'')
Example #27
0
 def _add_term(self,c,p):
     if type(c) not in (int, float):
         raise TypeError('Coefficient must be int or float, not type {}.'.format(type_as_str(type(c))))
     if type(p) != int:
         raise TypeError('Power must be type int. Type {} given.'.format(type_as_str(type(p))))
     if p < 0:
         raise TypeError('Power must be greater than 0. {} < 0.'.format(type_as_str(p)))
     if p not in self.terms.keys():
         self.terms[p] = c
     if p in self.terms.keys():
         self.terms[p] = c
         if self.terms[p] == 0:
             del self.terms[p]
Example #28
0
        def check_set():
            assert isinstance(value, type(annot)), \
            generic_assert.format(repr(param), repr(value),
                                  type_as_str(value), type_as_str(annot)) +'\n' + check_history
            assert len(annot) == 1, \
            f"{repr(param)} annotation inconsistency: {type_as_str(annot)} should have 1 value but had {len(annot)}\n\
  annotation = {annot}\n"                          + check_history

            for v in value:
                annot_v = list(annot)[0]
                self.check(
                    param, annot_v, v, check_history +
                    f'{type_as_str(annot)} value check: {annot_v}')
Example #29
0
    def __pow__(self,right):
        if type(right) is int or (type(right) is Dimensional and type(right['value']) is int and right['d'] == (0,0,0)):
#            if Dimensional._get_value(right) > 0:
            return Dimensional(self.value ** Dimensional._get_value(right),
                               *(x * Dimensional._get_value(right) for x in self['d']))
#            else:
#                return 1/Dimensional(self.value ** abs(Dimensional._get_value(right)),
#                                   *(x * abs(Dimensional._get_value(right)) for x in self['d']))
        if type(right) is not Dimensional:
            raise TypeError('unsupported operand type(s) for **'
                            ': \''+type_as_str(self)+'\' and \''+type_as_str(right)+'\'') 
        else:       
            raise DimensionError('incompatible dimensions for ** (2nd operand must be 0,0,0'
                            ': \''+str(self['d'])+'\' and \''+str(right['d'])+'\'')
Example #30
0
def batch_self_check(file_name,seperator='-->',show_exception_message=False):
    print('Starting batch_self_check')
    check_num, correct_count, wrong_count, wrong = 0, 0, 0, []
    for line in open(file_name):
        line = line.rstrip()
        check_num += 1
        try:
            # #
            if line[0] == '#':
                print(line)
                continue
            kind,to_compute,correct = line.split(seperator)
            # Command
            if kind =='c':
                exec(to_compute)
                correct_count += 1
            # Query/Expressions
            elif kind == 'e':
                computed = str(eval(to_compute))
                if correct != '':
                    if computed == correct:
                        correct_count += 1
                    else:
                        wrong_count += 1
                        wrong.append(check_num)
                        print(check_num,'Error:',to_compute,'->',computed,'but should ->',correct)
            # Exception expected
            elif kind == '^':
                try:
                    exec(to_compute)
                    wrong_count += 1
                    wrong.append(check_num)
                    print(check_num,'Error:',to_compute,'should have raised exception:', to_compute)
                except Exception as exc:
                    if any([isinstance(exc,eval(e)) for e in correct.split(',')]):
                        correct_count += 1
                        if show_exception_message:
                            print('  Correct exception('+type_as_str(exc)+'); message:',exc)
                    else:
                        wrong_count += 1
                        wrong.append(check_num)
                        print(check_num,'Error: Incorrect exception('+type_as_str(exc)+'); message:',exc)
                        
        except Exception:
            wrong_count += 1
            wrong.append(check_num)
            print(check_num,'Error:',to_compute,'raised exception')
            traceback.print_exc()
    print('\nDone batch_self_check:',correct_count,'correct;',wrong_count,'incorrect\n')
    print('Failed checks:',wrong)
Example #31
0
 def _add_term(self,c,p):
     if type_as_str(c) not in ["int",'float']:
         raise TypeError("{} is not int or float".format(str(c)))
     elif type_as_str(p) != 'int':
         raise TypeError("{} is not an int".format(str(p)))
     elif p < 0:
         raise TypeError("{} is < 0".format(str(p)))
     elif p not in self.terms and c != 0:
         self.terms[p] = c
     elif p in self.terms:
         if self.terms[p] + c == 0:
             self.terms.pop(c)
         else:
             self.terms[p] += c
Example #32
0
 def _add_term(self,c,p):
     if type(c) not in [int,float]:
         raise TypeError('unsupported type for polynomial coefficient:' + type_as_str(c))
     if type(p) is not int:
         raise TypeError('unsupported type for polynomial power:' + type_as_str(p))
     if p < 0:
         raise TypeError('given power was less than 0: ' + str(p))
     if p not in self.terms and c != 0:
         self.terms[p] = c
     elif p in self.terms:
         test_value = self.terms[p] + c
         if test_value == 0:
             self.terms.pop(p)
         else:
             self.terms[p] = test_value
Example #33
0
 def __init__(self,*terms):
     # __str__ uses the name self.terms for the dictionary of terms
     # So __init__ should build this dictionary from terms
     ''' coefficient, power '''
     self.terms = {}
     history_list = []
     for key, val in terms:
         assert type_as_str(key) in {'int','float'}
         assert type_as_str(val) == 'int'
         assert val >= 0
         if key != 0:
             history_list.append(val)
         assert history_list.count(val) <= 1
         if key != 0:
             self.terms[val] = key
Example #34
0
    def __init__(self, num=0, denom=1):
        assert (type(num), type(denom)) == (int, int), (
            'Rational.__init__, unsopported parameter types (num: ' +
            type_as_str(num) + ') and (denom: ' + type_as_str(denom) + ')')
        assert denom != 0, 'Rational.__init__, denom cannot be equal to 0 '
        if num == 0:
            self.num = 0
            self.denom = 1
        else:
            self.num = num // self._gcd(abs(num), abs(denom))
            self.denom = denom // self._gcd(abs(num), abs(denom))

        if self.denom < 0:
            self.num *= -1
            self.denom *= -1
Example #35
0
 def __rmul__(self, left):
     Fraction._validate_arithmetic(left, {Fraction, int}, '*', 'Fraction',
                                   type_as_str(left))
     if type(left) is Fraction:
         return Fraction(self.num * left.num, self.denom * left.denom)
     elif type(left) is int:
         return Fraction(self.num * left, self.denom)
Example #36
0
 def __eq__(self,right):
     if type(right) == Poly:
         return self.__repr__() == right.__repr__()
     elif type(right) in (int, float):
         return self.__len__() == 0 and self.terms[0] == right
     else:
         raise TypeError('Cannot compare type Poly to type {}'.format(type_as_str(right)))
Example #37
0
 def __delitem__(self,index):
     if type_as_str(index) != 'int':
         raise TypeError("{} is not an int".format(str(index)))
     elif index < 0:
         raise TypeError("{} is < 0".format(str(index)))
     if index in self.terms:
         self.terms.pop(index)
Example #38
0
 def __delitem__(self,index):
     if type(index) != int:
         raise TypeError('Power must be of type int; type {} given.'.format(type_as_str(index)))
     if index < 0:
         raise TypeError('Power must be greater than 0.')
     if index in self.terms:
         del self.terms[index]
 def __check_annotation__(self, check, param, value, text_history):
     assert isinstance(value, Bag), repr(param)+" failed annotation check(wrong type): value ="+repr(value)+\
     "\n  was type "+type_as_str(value)+" ...should be type Bag\n"+text_history
     for a in self.counts:
         pass
     for v in value.counts:
         check(param, a, v, text_history+"Bag value check: "+str(a)+"\n")
 def check_set_fset(t):
     assert isinstance(value,t), repr(param)+" failed annotation check(wrong type): value = "+repr(value)+\
     "\n  was type "+type_as_str(value)+" ...should be type "+str(t)+"\n"+check_history
     assert len(annot) == 1, repr(param)+" annotation inconsistency: "+str(t)+" should have 1 value but had "+str(len(annot))+\
     "\n  annotation = "+str(annot)
     for v in value:
         self.check(param, type(v), v, check_history+str(t)+" value check: "+str(annot))
Example #41
0
        def check_tuple():

            if type(annot) is tuple and isinstance(value, tuple) == False:
                raise AssertionError(
                    "'{a}' failed annotation check(wrong type): value = {v} was type {w} ...should be type tuple"
                    .format(a=str(param), v=str(value), w=type_as_str(value)))

            if len(annot) > 1:
                if len(value) != len(annot):
                    raise AssertionError(
                        "'{a}' failed annotation check(wrong number of elements): value = {v} annotation had {l}elements {e}"
                        .format(a=str(param),
                                v=str(value),
                                l=str(len(annot)),
                                e=str(annot)))

            counter = 0
            if len(annot) == 1:
                for i in value:
                    check_history = "list[{a}] check: {b}".format(a=counter,
                                                                  b=annot)
                    self.check(param, annot[0], i, check_history)

            counter = 0
            if len(annot) > 1:
                for i in value:
                    check_history = "list[{a}] check: {b}".format(
                        a=counter, b=annot[counter])
                    self.check(param, annot[counter], i, check_history)
                    counter += 1
 def __pow__(self, right):
     if type(right) is not int:
         raise TypeError('unsupported operand type(s) for +' + ': \'' +
                         type_as_str(self) + '\' and \'' +
                         type_as_str(right) + '\'')
     if right < 1:
         raise AssertionError('number must be greater than 0')
     if self.cols != self.rows:
         raise AssertionError(
             'Sparse_Matrix must be square(rows and columns must be equal)')
     nm = Sparse_Matrix(self.rows, self.cols)
     for idex in range(nm.rows):
         for indexs in range(nm.cols):
             power = int(self.matrix.get((idex, indexs), 0))**int(right)
             nm[idex, indexs] = power
     return nm
Example #43
0
 def __mul__(self,right):
     if type(right) is Poly:
         pass
     elif type_as_str(right) in ['int','float']:
         pass
     else:
         raise TypeError("{} is not Polynomial, int, or float".format(str(right)))
Example #44
0
 def __lt__(self,right):
     if type(right) is Point:
         return math.sqrt(self.x**2 + self.y**2) < math.sqrt(right.x**2+right.y**2)
     if type(right) is int or type(right) is float:
         return math.sqrt(self.x**2 + self.y**2) < right
     else:
         raise TypeError('Point.__lt__: right('+str(right)+') int or float('+type_as_str(right)+')')
Example #45
0
 def _add_term(self,c,p):
     
     if type_as_str(c) not in ['int', 'float']:
         raise AssertionError('Coefficient value must be of type int or float')
         
     elif type_as_str(p) != 'int' or p < 0:
         raise AssertionError('Power must be an int with value greater than or equal to 0')
     
     elif p not in self.terms and c != 0:
         self.terms[p] = c
     
     elif p in self.terms:
         self.terms[p] += c
         
         if self.terms[p] == 0:
             self.terms.pop(p)
Example #46
0
 def __getitem__(self, index):
     if type(index) in (int, str):
         if index in (0, 'x'):
             return self.x
         elif index in (1, 'y'):
             return self.y
         elif index in (2, 'z'):
             return self.z
         else:
             raise IndexError(type_as_str(self) + 'index out of range')
     elif type(index) is float:
         raise IndexError(type_as_str(self) + 'index out of range')
     else:
         raise TypeError('unsupported operand type(s) for __getitem__' +
                         ': \'' + type_as_str(self) + '\' and \'' +
                         type_as_str(index) + '\'')
Example #47
0
 def __sub__(self, right):
     Rational._validate_arithmetic(right, {Rational, int}, '-', 'Rational',
                                   type_as_str(right))
     if type(right) is int:
         right = Rational(right)
     return Rational((self.num * right.denom - right.num * self.denom),
                     (self.denom * right.denom))
Example #48
0
 def __rsub__(self, left):
     Rational._validate_arithmetic(left, {Rational, int}, '-', 'Rational',
                                   type_as_str(left))
     if type(left) is int:
         left = Rational(left)
     return Rational((left.num * self.denom - self.num * left.denom),
                     (self.denom * left.denom))
Example #49
0
 def __pow__(self, right):
     Fraction._validate_arithmetic(right, [int], '**', 'Fraction',
                                   type_as_str(right))
     if right >= 0:
         return Fraction(self.num**right, self.denom**right)
     else:
         return Fraction(self.denom**-right, self.num**-right)
Example #50
0
 def __add__(self, right):
     Fraction._validate_arithmetic(right, [Fraction, int], '+', 'Fraction',
                                   type_as_str(right))
     if type(right) is int:
         right = Fraction(right)
     return Fraction(self.num * right.denom + right.num * self.denom,
                     self.denom * right.denom)
Example #51
0
 def __getitem__(self,index):
     if type_as_str(index) != 'int':
         raise TypeError("{} is not an int".format(str(index)))
     elif index < 0:
         raise TypeError("{} is < 0".format(str(index)))
     elif index not in self.terms:
         return 0
     return self.terms[index]
Example #52
0
 def __getitem__(self,index):
     if type_as_str(index) != 'int' or int(index) < 0:
         raise TypeError('Poly.__getitem__: illegal index')
     
     if index in self.terms.keys():
         return self.terms[index]
     else:
         return 0
Example #53
0
 def __rmul__(self,left):
     
     answer = Poly()
     
     if 'Poly' not in type_as_str(self) or type_as_str(left) not in ['int', 'float']\
      and 'Poly' not in type_as_str(left):
         
         raise TypeError('Operands must be of type Poly and Poly or int or float')
     
     elif 'Poly' in type_as_str(self) and 'Poly' in type_as_str(left):
         pass
                 
     else:
         for power in self.terms:
             answer._add_term(self.terms[power] * left, power)
             
     return answer
 def check_dict():
     assert isinstance(value,dict), repr(param)+" failed annotation check(wrong type): value = "+repr(value)+\
     "\n  was type "+type_as_str(value)+" ...should be type dict\n"+check_history
     assert len(annot) == 1, repr(param)+" annotation inconsistency: dict should have 1 item but had "+str(len(annot))+\
     "\n  annotation = "+str(annot)
     for k,v in value.items():
         self.check(param, list(annot.keys())[0], k, check_history+"dict key check: "+str(list(annot.keys())[0])+"\n")
         self.check(param, list(annot.values())[0], v, check_history+"dict value check: "+str(list(annot.values())[0])+"\n")
Example #55
0
 def __rmul__(self,left):
     if type(left) in (int, float):
         result = Poly()
         for p, c in self.terms.items():
             result._add_term(c * left, p)
         return result
     else:
         raise TypeError('Cannot multiply type {} to type Poly'.format(type_as_str(left)))
Example #56
0
 def __delitem__(self,index):
     if type(index) is not int:
         raise TypeError('unsupported type for __delitem__ :' + type_as_str(index))
     if index < 0:
         raise TypeError('given power was less than 0: ' + str(index))
     if index not in self.terms:
         pass
     else:
         self.terms.pop(index)