Exemplo n.º 1
0
    def test_individual_operations(self):
        value = Interpreter().visit(AddNode(NumberNode(27), NumberNode(14))
        self.assertEqual(value, Number(41))  

        value = Interpreter().visit(SubtractNode(NumberNode(27), NumberNode(14))
        self.assertEqual(value, Number(13))        

        value = Interpreter().visit(MultiplyNode(NumberNode(27), NumberNode(14))
        self.assertEqual(value, Number(378)) 

        value = Interpreter().visit(DivideNode(NumberNode(27), NumberNode(14))
        self.assertEqual(value.value, 1.92857, 5))  

        with self.assertRaises(Exception):
            Interpreter().visit(DivideNode(NumberNode(27), NumberNode(0)))

    def test_full_expression(self):
       tree=AddNode(
            NumberNode(27),
            MultiplyNode(
                SubtractNode(
                    DivideNode(
                        NumberNode(43),
                        NumberNode(36),
                    ),
                    NumberNode(48),
                ),
                NumberNode(51),
            )
        )
        result = Interpreter().visit(tree)            
        self.assertAlmostEqual(result.value, -2360.08, 2)
Exemplo n.º 2
0
class Timer(object):
    def __init__(self, x, y, f):
        self.x = x
        self.y = y
        self.f = f
        self.runButton = Button(self.x - 26 * self.f, self.y, "play")
        self.helpButton = Button(self.x + 2 * 26 * self.f, self.y, "help")
        self.automatic = False
        self.start()

    ''' reset timer and set running to true '''

    def start(self):
        self.time = Number(0, self.x, self.y)
        self.running = True
        return self.time.value

    ''' only update when timer should be running .. '''

    def update(self, dt):
        if self.running:
            ''' if the runbutton was pressed, toggle automatic '''
            if self.runButton.bang:
                self.automatic = not self.automatic
                self.runButton.bang = False
            ''' if the helpbutton was pressed, display hint '''
            if self.helpButton.bang:
                SingleStepSolver(self.playerBoard)
                self.helpButton.bang = False
            ''' increment timer, call a new hint if automatic mode is on '''
            self.time.value = min(999, self.time.value + .1)
            if self.automatic:
                if SingleStepSolver(self.playerBoard) == "stop":
                    self.automatic = False

    def stop(self):
        self.running = False

    ''' pass mouse queues to buttons '''

    def pressed(self, x, y, button, mouse, f):
        self.runButton.pressed(x, y, button, mouse, f)
        self.helpButton.pressed(x, y, button, mouse, f)

    def released(self, x, y, button, mouse, f):
        self.runButton.released(x, y, button, mouse, f)
        self.helpButton.released(x, y, button, mouse, f)

    ''' draw all included objects '''

    def draw(self, images):
        self.time.draw(images, self.f)
        self.runButton.draw(images)
        self.helpButton.draw(images)
Exemplo n.º 3
0
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.number = Number.Number(1)
        numberFromLabel = QLabel("Number:")
        self.numberFromLine = QLineEdit()
        baseFromLabel = QLabel("From Base:")
        self.baseFromLine = QLineEdit()
        baseToLabel = QLabel("To Base:")
        self.baseToLine = QLineEdit()
        self.submitButton = QPushButton("Convert!")
        self.resultLabel = QLabel("")

        vLayout1 = QVBoxLayout()
        vLayout1.addWidget(numberFromLabel)
        vLayout1.addWidget(self.numberFromLine)
        vLayout1.addWidget(baseFromLabel)
        vLayout1.addWidget(self.baseFromLine)
        vLayout1.addWidget(baseToLabel)
        vLayout1.addWidget(self.baseToLine)
        vLayout1.addWidget(self.submitButton)
        vLayout1.addWidget(self.resultLabel)

        self.submitButton.clicked.connect(self.submitNumbers)

        mainLayout = QGridLayout()
        mainLayout.addLayout(vLayout1, 0, 1)

        self.setLayout(mainLayout)
        self.setWindowTitle("Base converter")
Exemplo n.º 4
0
   def __init__(self):
      self.Scale = self.SCALE
      self.OneDegree = 6.3 / 360
      self.FrameStep = 0.1      
      self.xMax = 0
      self.yMax = 0
      self.xOffset = self.HYPERSPACE
      self.yOffset = self.HYPERSPACE
      self.xVelocity = 0
      self.yVelocity = 0
      self.Crash = False
      self.ThrustFlag = False
      self.Fade = 0
      self.Lives = self.MAX_LIVES
      self.ExplodeFrame = 0
      self.ShotIndex = 0
      self.HyperCount = False

      self.PlayerScore = Number.Number()

      self.Shots = [AstroShot.AstroShot() for X in range(self.MAX_SHOTS)]
      self.LifeFrame = [Common.XPoint() for X in range(self.FRAME_POINTS)]
      self.LifeDisplayFrame = [Common.XPoint() for X in range(self.FRAME_POINTS)]
      self.Frame = [[Common.XPoint() for X in range(self.FRAME_POINTS)] for Y in range(self.FRAMES)]
      self.DisplayFrame = [Common.XPoint() for X in range(self.FRAME_POINTS * 2)]
      self.OldFrame = [Common.XPoint() for X in range(self.FRAME_POINTS * 2)]
      self.ExplodeDirection = [Common.XPoint() for X in range(self.FRAME_POINTS * 2)]
      self.ThrustTrail = [Common.XPoint() for X in range(self.THRUST_POINTS)]

      self.ShotWav = pygame.mixer.Sound("Sounds/Shot.wav")
      self.ThrustWav = pygame.mixer.Sound("Sounds/Thrust.wav")
      self.ShipBlow = pygame.mixer.Sound("Sounds/ShipBlow.wav")
      self.HyperSpaceWav = pygame.mixer.Sound("Sounds/HyperSpace.wav")

      self.Angle = self.SHIP_START_ANGLE
      self.LifeFrame[0].x = self.Scale * 19 * math.sin(self.FrameStep * self.Angle + self.OneDegree * 0)
      self.LifeFrame[0].y = self.Scale * 19 * math.cos(self.FrameStep * self.Angle + self.OneDegree * 0)
      self.LifeFrame[1].x = self.Scale * 16 * math.sin(self.FrameStep * self.Angle + self.OneDegree * 140)
      self.LifeFrame[1].y = self.Scale * 16 * math.cos(self.FrameStep * self.Angle + self.OneDegree * 140)
      self.LifeFrame[2].x = self.Scale * 8 * math.sin(self.FrameStep * self.Angle + self.OneDegree * 180)
      self.LifeFrame[2].y = self.Scale * 8 * math.cos(self.FrameStep * self.Angle + self.OneDegree * 180)
      self.LifeFrame[3].x = self.Scale * 16 * math.sin(self.FrameStep * self.Angle + self.OneDegree * 220)
      self.LifeFrame[3].y = self.Scale * 16 * math.cos(self.FrameStep * self.Angle + self.OneDegree * 220)
      self.LifeFrame[4].x = self.Scale * 19 * math.sin(self.FrameStep * self.Angle + self.OneDegree * 0)
      self.LifeFrame[4].y = self.Scale * 19 * math.cos(self.FrameStep * self.Angle + self.OneDegree * 0)

      for self.Angle in range(self.FRAMES):
         self.Frame[self.Angle][0].x = self.Scale * 16 * math.sin(self.FrameStep * self.Angle + self.OneDegree * 0)
         self.Frame[self.Angle][0].y = self.Scale * 16 * math.cos(self.FrameStep * self.Angle + self.OneDegree * 0)
         self.Frame[self.Angle][1].x = self.Scale * 13 * math.sin(self.FrameStep * self.Angle + self.OneDegree * 140)
         self.Frame[self.Angle][1].y = self.Scale * 13 * math.cos(self.FrameStep * self.Angle + self.OneDegree * 140)
         self.Frame[self.Angle][2].x = self.Scale * 5 * math.sin(self.FrameStep * self.Angle + self.OneDegree * 180)
         self.Frame[self.Angle][2].y = self.Scale * 5 * math.cos(self.FrameStep * self.Angle + self.OneDegree * 180)
         self.Frame[self.Angle][3].x = self.Scale * 13 * math.sin(self.FrameStep * self.Angle + self.OneDegree * 220)
         self.Frame[self.Angle][3].y = self.Scale * 13 * math.cos(self.FrameStep * self.Angle + self.OneDegree * 220)
         self.Frame[self.Angle][4].x = self.Scale * 16 * math.sin(self.FrameStep * self.Angle + self.OneDegree * 0)
         self.Frame[self.Angle][4].y = self.Scale * 16 * math.cos(self.FrameStep * self.Angle + self.OneDegree * 0)

      self.Angle = self.SHIP_START_ANGLE
Exemplo n.º 5
0
 def execInputInt(self, execCtX):
     while True:
         text = input()
         try:
             number = int(text)
             break
         except ValueError:
             print("'{}' must be an integer. Try again!".format(text))
     return RTResult().success(Number(number))
Exemplo n.º 6
0
 def run_44(self):  # проверка у на простоту
     try:
         if '.' in self.lineEdit.text():
             y = float(self.lineEdit_2.text())
         else:
             y = int(self.lineEdit_2.text())
         self.lcdNumber.display(Number.IsPrime(y))
     except Exception:
         self.lcdNumber.display('Error')
Exemplo n.º 7
0
    def execLen(self, execCtX):
        list_ = execCtX.symbTable.get("list")

        if not isinstance(list_, List):
            return RTResult().failure(
                RTError(self.startPos, self.endPos, "Argument must be list",
                        execCtX))

        return RTResult().success(Number(len(list_.elements)))
Exemplo n.º 8
0
 def run_43(self):  # проверка х на простоту
     try:
         if ',' in self.lineEdit.text():
             self.lineEdit.text().replace(',', '.')
         if '.' in self.lineEdit.text():
             x = float(self.lineEdit.text())
         else:
             x = int(self.lineEdit.text())
         self.lcdNumber.display(Number.IsPrime(x))
     except Exception:
         self.lcdNumber.display('Error')
Exemplo n.º 9
0
 def getRationalRoots(self):
     coeffs = self.getConstantCoefficients()
     lcm = Number.NumberLCMList([
         (x._q if type(x) == Number.Rational else
          (1 if isInt(x) else Number.Rational.fromFloat(x)._q))
         for x in coeffs
     ])
     newCoeffs = mulObjectToListElements(lcm, coeffs)
     lc = newCoeffs[len(coeffs) - 1]
     ac = newCoeffs[0]
     ps = Number.getAllDivisors(int(abs(ac)))
     qs = Number.getAllDivisors(int(abs(lc)))
     roots = []
     for p in ps + map(lambda x: -x, ps):
         for q in qs:
             x = Number.Rational(p, q)
             v = self.evaluate(x)
             if v == 0:
                 if x not in roots:
                     roots.append(x)
     return roots
Exemplo n.º 10
0
 def solveError(self, list):
     for i, token in enumerate(list):
         if i + 2 < len(list):
             if list[i].type == 'operator' and list[i + 1].type == 'operator' \
             and list[i + 2].operand == 1 and list[i + 1].value == '-':
                 if isinstance(list[i + 2], Number):
                     del list[i + 1]
                     list[i + 1] = Number(str(list[i + 1].value * -1))
                 elif isinstance(list[i + 2], Complex):
                     del list[i + 1]
                     list[i + 1] = Complex(real=list[i + 1].real * -1,
                                           img=list[i + 1].img * -1)
         if i + 1 < len(list) and i == 0 and list[
                 i].type != 'Matrice' and list[i].value == '-' and list[
                     i + 1].operand == 1:
             if isinstance(list[i + 1], Number):
                 del list[i]
                 list[i] = Number(str(list[i].value * -1))
             elif isinstance(list[i + 1], Complex):
                 del list[i]
                 list[i] = Complex(real=list[i].real * -1,
                                   img=list[i].img * -1)
Exemplo n.º 11
0
 def __sub__(self, other):
     if isinstance(other, N.Number):
         realPart = self.real - other.value
         return Complex(real=realPart, img=self.img)
     if isinstance(other, Complex):
         realPart = self.real - other.real
         imgPart = self.img - other.img
         if imgPart:
             return Complex(real=realPart, img=imgPart)
         else:
             return N.Number(realPart)
     else:
         print('\033[31mInvalid operation [-] between', self.type, 'and',
               other.type, '\033[0m')
Exemplo n.º 12
0
 def __pow__(self, other):
     if isinstance(other, N.Number):
         realPart = self.real**other.value
         imgPart = self.img**other.value
         powerI = other.value
         c = complex(self.real, self.img)
         c = c**other.value
         if c.imag:
             return Complex(real=c.real, img=c.imag)
         else:
             return N.Number(str(c.real))
     else:
         print('\033[31mInvalid operation [^] between', self.type, 'and',
               other.type, '\033[0m')
Exemplo n.º 13
0
 def __mul__(self, other):
     if isinstance(other, N.Number):
         realPart = other.value * self.real
         imgPart = other.value * self.img
         return Complex(real=realPart, img=imgPart)
     if isinstance(other, Complex):
         realPart = self.real * other.real - self.img * other.img
         imgPart = self.real * other.img + self.img * other.real
         if imgPart:
             return Complex(real=realPart, img=imgPart)
         else:
             return N.Number(realPart)
     else:
         print('\033[31mInvalid operation [*] between', self.type, 'and',
               other.type, '\033[0m')
Exemplo n.º 14
0
    def visit_UnaryOpNode(self, node, context):
        res = RTResult()
        number = res.register(self.visit(node.node, context))
        if res.error: return res

        error = None

        if node.op_tok.type == TT_MINUS:
            number, error = number.multed_by(Number(-1))
        elif node.op_tok.matches(TT_KEYWORD, 'NOT'):
            number, error = number.notted()

        if error:
            return res.failure(error)
        else:
            return res.success(number.set_pos(node.pos_start, node.pos_end))
Exemplo n.º 15
0
 def __init__(self, e):
     self.item = translate(e)
     self.lock = False
     items = [Number(min_range=-10, max_range=10, bucket_count=100)
              ] + xfr_fxns + red_fxns
     self.buckets = []
     for i in items:
         self.buckets.append({
             'item': i,
             'last_sample': None,
             'x_samples': [],
             'scores': [],
             'avg': None
         })
         if isinstance(i, Number):
             self.number_bucket = self.buckets[-1]
     self.lastest_bucket = None
Exemplo n.º 16
0
    def getRoots(self):
        coeffs = self.getConstantCoefficients()
        if coeffs == None:
            raise NotImplementedError()
        if self.degree > 2:
            raise NotImplementedError()

        if self.degree == 1:
            return [-coeffs[0] / coeffs[1]]
        elif self.degree == 2:
            a = coeffs[2]
            p = coeffs[1] / a
            q = coeffs[0] / a
            rad = (p / 2)**2 - q
            disc = Number.sqrt(rad)
            zero0 = -p / 2 + disc
            zero1 = -p / 2 - disc
            return [zero0, zero1]
Exemplo n.º 17
0
 def __mod__(self, other):
     if isinstance(other, N.Number):
         realPart = other.value % self.real
         return Complex(real=realPart, img=self.img)
     if isinstance(other, Complex):
         realPart = (
             (self.real * other.real) +
             (self.img * other.img)) % (other.real**2 + other.img**2)
         imgPart = (
             (self.img * other.real) -
             (self.real * other.img)) % (other.real**2 + other.img**2)
         if imgPart:
             return Complex(real=realPart, img=imgPart)
         else:
             return N.Number(realPart)
     else:
         print('\033[31mInvalid operation [%] between', self.type, 'and',
               other.type, '\033[0m')
Exemplo n.º 18
0
def process_board(image, dimensions):
    corners = Grid.board_corners(preprocess_image(image.copy(), 3))
    cropped_grid = Grid.crop_reshape(preprocess_image(image.copy(), 1), corners)

    expand_ratio = 1.05
    squares = expanded_squares(cropped_grid.copy(), expand_ratio)

    centered_numbers = []
    for square in squares:
        number = Number.PreprocessNumber(square.copy())
        number.crop_feature()
        if number.is_number():
            centered_number = number.get_centered_number(dimensions)
        else:
            centered_number = np.zeros(dimensions)
        centered_numbers.append(centered_number)

    return centered_numbers
Exemplo n.º 19
0
    def can_become(self, index):
        prev_item = self.elements[index].item
        prev_lock = self.elements[index].lock
        self.elements[index].lock = True
        possibles = []

        self.elements[index].item = xfr_fxns[0]
        if self.validate(locked_only=True):
            possibles += xfr_fxns
        self.elements[index].item = red_fxns[0]
        if self.validate(locked_only=True):
            possibles += red_fxns
        self.elements[index].item = 1.0
        if self.validate(locked_only=True):
            # TODO: This then becomes a new random Number() or Input() chosen from input list <-- start here
            possibles += [
                Number(min_range=-10, max_range=10, bucket_count=100)
            ]

        self.elements[index].item = prev_item
        self.elements[index].lock = prev_lock

        return possibles
Exemplo n.º 20
0
def translate(x):
    if floats(x):
        # TODO: If type == Input() class then return x
        return float(x)
    elif x[:2] == 'n':
        return Number(min_range=-10, max_range=10, bucket_count=100)
    elif x == "-":
        return np.subtract
    elif x == "+":
        return np.add
    elif x == "/":
        return np.divide
    elif x == "*":
        return np.multiply
    elif x == "pow":
        return np.power
    elif x == "sin":
        return np.sin
    elif x == "cos":
        return np.cos
    elif x == "tan":
        return np.tan
    elif x == "exp":
        return np.exp
Exemplo n.º 21
0
 def parseNumber(self, t):
     return Number.Number(t, self.parsingConversion)
Exemplo n.º 22
0
        return self.__str__()


if __name__ == '__main__':
    from Parse import *

    [a, b, c] = FE.Variables(['a', 'b', 'c'])
    mi1 = MultiIndex(data=[(a, 5), (b, 4)])
    mi2 = MultiIndex(data=[(b, -1)])
    print(mi1,
          mi2,
          mi1 + mi2,
          -mi2,
          mi1 == MultiIndex(data=[(a, 5), (b, 4)]),
          sep="\n")
    mon1 = ExtendedMultivariateMonomial(coefficient=Number.Rational(42, 1),
                                        multiIndex=mi1)
    mon2 = ExtendedMultivariateMonomial(coefficient=Number.Rational(-1, 1),
                                        multiIndex=mi2)
    pol1 = ExtendedMultivariatePolynomial(terms=[mon1, mon2])
    pol2 = ExtendedMultivariatePolynomial(
        terms=[ExtendedMultivariateMonomial(coefficient=3, multiIndex=mi2)])
    print(mon1, mon2, pol1, pol2, pol1 + pol2, pol1 * pol2, sep="\n")

    fe1 = FE.FieldExtension(FE.TRANS_EXP, Pol.Polynomial([0, Number.ONE]),
                            FE.Variable('T_1'))
    ft = FE.FieldTower(fe1)
    fe2 = FE.FieldExtension(FE.TRANS_LOG,
                            Pol.Polynomial([0, Number.ONE], fieldTower=ft),
                            FE.Variable('T_2'))
    FE.fieldTower = FE.FieldTower(fieldExtensions=[fe1, fe2])
Exemplo n.º 23
0
		if value == None and self.parent:
			return self.parent.get(name)
		return value

	def set(self, name, value):
		self.symbols[name] = value

	def remove(self, name):
		del self.symbols[name]





global_symbol_table = SymbolTable()
global_symbol_table.set("NULL", Number(0))
global_symbol_table.set("FALSE", Number(0))
global_symbol_table.set("TRUE", Number(1))


#######################################
# RUN
#######################################

def run(fn, text):
	# Generate tokens
	lexer = Lexer(fn, text)
	tokens, error = lexer.make_tokens()
	if error: return None, error
	
	# Generate AST
Exemplo n.º 24
0
# 객체지향 프로그래밍 12주차 과제 : 계산기 프로그램 , 컴퓨터공학과 2학년 1826052 최영서
import os

from Number import *
from Menu import *

contents = Number.OperatorMessage
printmenu = Menu(contents)

while not printmenu.isExit():
    printmenu.print()
    printmenu.getMenuNumber()

    print("\n\n")
    op1 = Number("\t첫번째 숫자를 입력하세요")
    op2 = Number("\t두번째 숫자를 입력하세요")

    messageHead = Number.OperatorMessage[printmenu.MenuNumber - 1]
    operator = Number.Operator[printmenu.MenuNumber - 1]
    expression = f"{op1} {operator} {op2}"
    result = eval(expression)
    print(f"\t{messageHead} : {op1} {operator} {op2} = {result}")
    input("\t\t계속하려면 엔터를 누르세요")
Exemplo n.º 25
0
 def visit_NumberNode(self, node, context):
     return RTResult().success(
         Number(node.tok.value).set_context(context).set_pos(
             node.pos_start, node.pos_end))
Exemplo n.º 26
0
    resultObj = GetTitleAndURL(TED_ID)
    resultObj[u"paragraphs"] = obj
    result = json.dumps(resultObj, ensure_ascii=False, sort_keys=True)

    baseDirPath = 'output/'
    filePath = '%s/%s.json' % (baseDirPath, TED_ID)
    WriteFileContent(filePath, result)
    filePath = '%s/%s.srt' % (baseDirPath, TED_ID)
    WriteFileContent(filePath, srtTexts)


if DebugTagType.PrintSubtitles in debugTags:
    PrintResult(filteredEnglishSubtitles, filteredChineseSubtitles)

if DebugTagType.File in debugTags:
    contentsInFile = ReadFileContent(filePath)
    lengthForChineseSubtitles = len(filteredChineseSubtitles)
    idxForChineseSubtitles = 0
    i = 0
    while i < len(contentsInFile):
        if Number.IsInt(contentsInFile[i]):
            i += 2
            hasTranslated = len(contentsInFile[i]) > 0 or True
            if hasTranslated:
                contentsInFile[i] = filteredChineseSubtitles[
                    idxForChineseSubtitles].content.encode('utf8')
            idxForChineseSubtitles += 1
        i += 1

    WriteFileContent(filePath, '\n'.join(contentsInFile))
Exemplo n.º 27
0
import Number

_0 = Number.ZERO
_1 = Number.ONE
_2 = _1 + _1
_3 = _2 + _1
_4 = _2 * _2
x = Number.fromInt(345)
y = Number.fromInt(-125)

print(_0)
print(_1)
print(_2)
print(_3)
print(_4)
print(-_4)

print(hash(_4))
print(_4.sign())
print((-_4).sign())
print(_0.sign())
print(x + y)
print("random number = %s" % Number.random(8))
z = Number.fromInt(2 ** 256)
t = -z
print(z)
print(t)
u = z.toBytes(33)
v = t.toBytes(33)

print(u)
Exemplo n.º 28
0
 def test_numbers(self):
     value = Interpreter().visit(NumberNode(51.2))
     self.assertEqual(value, Number(51.2))
Exemplo n.º 29
0
    def parse(self, strInput):
        """ Detect les element et les insere dans une liste """

        strInput = strInput.replace(' ', '')
        strInput = strInput.replace('+-', '-')
        strInput = self.replacePowerI(strInput)
        i = 0
        list = []
        error = str()
        while i < len(strInput):
            if re.match('-i', strInput[i:]):
                find = re.search('-i', strInput[i:]).group(0)
                i += len(find) - 1
                list.append(Complex(real=0, img=-1))
            elif re.match('\d+?\*?i', strInput[i:]):
                find = re.search('\d+?\*?i', strInput[i:]).group(0)
                i += len(find) - 1
                list.append(Complex(find))
            elif re.match('\d+\.\d+\*?i', strInput[i:]):
                find = re.search('\d+\.\d+\*?i', strInput[i:]).group(0)
                i += len(find) - 1
                list.append(Complex(find))
            elif re.match('i', strInput[i:]):
                find = re.search('i', strInput[i:]).group(0)
                i += len(find) - 1
                list.append(Complex(find))
            elif re.match('\d+\.\d+', strInput[i:]):
                find = re.search('\d+\.\d+', strInput[i:]).group(0)
                i += len(find) - 1
                list.append(Number(find, 'float'))
            elif re.match('\d+', strInput[i:]):
                find = re.search('\d+', strInput[i:]).group(0)
                i += len(find) - 1
                list.append(Number(find, 'int'))
            elif re.match('[a-zA-Z]+\([a-zA-Z]+\)', strInput[i:]):
                find = re.search('[a-zA-Z]+\([a-zA-Z]+\)',
                                 strInput[i:]).group(0)
                i += len(find) - 1
                if 'i' in find:
                    error = "\033[31mA function cannot contain i\033[0m"
                list.append(Element(find, 'defFunction'))
            elif re.match('[a-zA-Z]+\(\-?\d+\)', strInput[i:]):
                find = re.search('[a-zA-Z]+\(\-?\d+\)', strInput[i:]).group(0)
                i += len(find) - 1
                if 'i' in find:
                    error = "\033[31mA function cannot contain i\033[0m"
                list.append(Element(find, 'callFunction'))
            elif re.match('[a-zA-Z]+', strInput[i:]):
                find = re.search('[a-zA-Z]+', strInput[i:]).group(0)
                i += len(find) - 1
                if 'i' in find:
                    error = "\033[31mA variable cannot contain i\033[0m"
                list.append(Element(find, 'var'))
            elif strInput[i] == '[':
                find = Matrice.getMatrice(strInput[i:])
                i += len(find) - 1
                matrice = Matrice(find)
                if not matrice.valid:
                    error = "\033[31mInvalid Matrice:\033[0m " + find
                list.append(matrice)
            elif re.match('\*\*', strInput[i:]):
                find = re.search('\*\*', strInput[i:]).group(0)
                i += len(find) - 1
                list.append(Element(find, 'operator'))
            elif strInput[i] in '+-*/%^=?()':
                list.append(Element(strInput[i], 'operator'))
            else:
                error = "\033[31mInvalid input:\033[0m " + strInput[i]
            i += 1
            if not error == "":
                break
        self.solveError(list)
        if error == "":
            error = self.checkError(strInput)
        return list, error
Exemplo n.º 30
0
from Number import *

op1 = Number("첫번째 숫자를 입력하세요")
op2 = Number("두번째 숫자를 입력하세요")

messageHead = Number.OperatorMessage[0]
print(f"\t{messageHead} : {op1} + {op2} = {op1 + op2}")


messageHead = Number.OperatorMessage[3]
operator = Number.Operator[3]
expression = f"{op1} {operator} {op2}"
result = eval(expression)
print(f"\t{messageHead} : {op1} {operator} {op2} = {result}")
Exemplo n.º 31
0
            return n
        return "{}+{}".format(n, p)


def extPolyFromPolys(normPoly, princPoly, variable):
    return ExtendedPolynomial(normPoly.getCoefficients(),
                              princPoly.getCoefficients()[1:princPoly.degree +
                                                          1],
                              variable=variable)


def extPolyFromPol_power(poly, power):  # poly/T^power
    extPoly = ExtendedPolynomial(variable=poly.variable)
    for i in range(poly.degree, -1, -1):
        extPoly.setCoefficient(i - power,
                               poly.getCoefficient(i),
                               callUpdates=False)
    return extPoly


if __name__ == '__main__':
    o = Number.Rational(1, 1)
    fieldTower = FE.FieldTower(
        FE.FieldExtension(FE.TRANS_EXP, Pol.Polynomial([0, o]), "T_1"))
    pol = ExtendedPolynomial([o, 2 * o], [-o, 42 * o],
                             fieldTower)  # 2T_1 + 1 + -1/T_1 + 42*1/T_1**2
    print(pol.printFull())
    pol2 = pol.mulByMonicMonomial(1)  #2T_1**2 + 1T_1 + -1 + 42*1/T_1
    print(pol2.printFull())
    pol3 = pol.mulByMonicMonomial(2)
    print(pol3.printFull())