def _parseOperand(self, operand): retval = None rettype = OperandType.NONE # First try symbol lookup. entry = self.context.symtab.lookup(operand) if entry != None: retval = entry.value rettype = OperandType.SYMBOLIC self.length = entry.length self.refType = entry.type else: tmpop = operand if self.addressExpr and (operand.startswith('+') or operand.startswith('-')): tmpop = operand[1:] try: # Next try number. op = Number(tmpop) if op.isValid(): retval = op.value rettype = OperandType.DECIMAL self.refType = RecordType.CONST except: # Assume it is a symbol as yet undefined. pass return (retval, rettype)
def primary(self): ''' primary := hex_number | binary_number | octal_number | decimal_number | '(' start_expr ')' ''' if self._accept(TokenType.DECIMAL): if self.currentToken.type != TokenType.DECIMAL: raise SyntaxError( f'Expected decimal number, got {self.currentToken.value}') return Number().fromString(self.currentToken.value) if self._accept(TokenType.HEX): if self.currentToken.type != TokenType.HEX: raise SyntaxError( f'Expected hex number, got {self.currentToken.value}') return Number().fromString(self.currentToken.value) if self._accept(TokenType.BINARY): if self.currentToken.type != TokenType.BINARY: raise SyntaxError( f'Expected binary number, got {self.currentToken.value}') return Number().fromString(self.currentToken.value) if self._accept(TokenType.OCTAL): if self.currentToken.type != TokenType.OCTAL: raise SyntaxError( f'Expected octal number, got {self.currentToken.value}') return Number().fromString(self.currentToken.value) elif self._accept(TokenType.LPAREN): result = self.startExpr() self._expect(TokenType.RPAREN) return result else: raise SyntaxError(f'Got unexpected token {self.nextToken.value}')
def test_can_shift_right(self): value = Number().fromNumber(0b11010100) result = value >> Number().fromNumber(1) self.assertEqual(0b1101010, result.number) self.assertEqual("0110 1010", result.asBinary)
def print_gl(self): if self._active_actor is not None: self._draw_square(self._active_actor.position, 0, 0.5, 0) for target in self._active_actor_targets: self._draw_square(target.position, 0.5, 0, 0) for in_range in self._active_actor_range: self._draw_square(in_range, 0, 0, 0.5) if self._range_paths is not None: visited = self._range_paths[0] max_weight = max(visited.values()) for (x, y) in visited: weight = visited[(x, y)] Number.draw(weight, (x, y), self.state.height) intensity = weight / float(max_weight) self._draw_square((x, y), intensity, 0, intensity, 0.5) if self._active_actor_selected_next_square is not None: x, y = self._active_actor_selected_next_square self._draw_square((x, y), 0, 0.8, 0) if self._victim is not None: x, y = self._victim.position self._draw_square((x, y), 0.5, 0, 0.5, 0.5)
def test_can_shift_left(self): value = Number().fromNumber(0b1101010) result = value << Number().fromNumber(1) self.assertEqual(0b11010100, result.number) self.assertEqual("1101 0100", result.asBinary)
def generate_tape(self, size, ctx, secret_key): indices = [] # Encrypt indices before feeding into VM for x in range(size): self.add_cell(Number.from_plaintext(0, ctx, secret_key)) indices.append(Number.from_plaintext(x, ctx, secret_key)) return indices
def test_can_and(self): left = Number().fromNumber(0b110101) right = Number().fromNumber(0b1) result = left & right self.assertEqual(0x01, result.number) self.assertEqual("0001", result.asBinary)
def test_can_or(self): left = Number().fromNumber(0b110101) right = Number().fromNumber(0b11) result = left | right self.assertEqual(0b110111, result.number) self.assertEqual("0011 0111", result.asBinary)
def test_can_multiply_with_negative_result(self): left = Number().fromNumber(0x17) right = Number().fromNumber(-0x07) result = left * right self.assertEqual(-0xA1, result.number) self.assertEqual("-00A1", result.asHex)
def test_can_add_with_positive_result(self): left = Number().fromNumber(0x17) right = Number().fromNumber(0x07) result = left + right self.assertEqual(0x1E, result.number) self.assertEqual("001E", result.asHex)
def test_can_divide_with_negative_result(self): left = Number().fromNumber(-0x10) right = Number().fromNumber(0x04) result = left // right self.assertEqual(-0x04, result.number) self.assertEqual("-0004", result.asHex)
def test_can_subtract_with_positive_result(self): left = Number().fromNumber(0x20) right = Number().fromNumber(0x10) result = left - right self.assertEqual(16, result.number) self.assertEqual("0010", result.asHex)
def main(): a = Number(Digits.eight) b = Number(Digits.seven) print(f"{a} + {b} = {a + b}") print(f"{a} * {b} = {a * b}") print(f"{a} ** {b} = {a ** b}") print()
def test_number_equality(): n = 10 number = Number(10) assert number == n other = Number(n) assert number == other
async def run(self, first=3, second=5): tasks = [ Number(value=first), Number(value=second) ] result = min(await join(tasks)) print('Minimum value:', result) return result
def __init__(self, number, session_obj=None): """The constructor for this class takes in a number and saves it as an attribute. It also creates a list of digits that make up that number, as well as a list of factors of the number, and saves those lists as attributes.""" self.number = number self.digits = [int(d) for d in str(self.number) if d != '-'] self.factors = [i for i in range(1, self.number + 1) if self._is_factor(self.number, i)] self.hints = [] self.app_text = AppText() self.num_obj = Number() self.session_obj = session_obj
def test_binary(self): one = Number.create_binary_array(1, 8) two = Number.create_binary_array(2, 8) three = Number.create_binary_array(3, 8) two56 = Number.create_binary_array(256, 8) flag = Number.create_binary_array(1, 1) self.assertEqual(two56, [[1],[0],[0],[0],[0],[0],[0],[0]]) self.assertEqual(one, [[0],[0],[0],[0],[0],[0],[0],[1]]) self.assertEqual(two, [[0],[0],[0],[0],[0],[0],[1],[0]]) self.assertEqual(three, [[0],[0],[0],[0],[0],[0],[1],[1]]) self.assertEqual(flag, [[1]])
def find_primes(start, end, count=None): primes = [] print "Find '%s' primes from '%s' to '%s'" % (count if count is not None else 'all', start, end) for num in range(start, end + 1): number = Number(num) if number.is_prime(): primes.append(num) if count is not None and len(primes) >= count: break return primes
def test_number_validity(): small_big_numbers = [ 12, 1473, # trigger 2, 8, 19, 2477, # trigger 3, ] number = Number() for my_number in small_big_numbers: assert number.verify_number(my_number) == True, "number must be less than 100!"
def rpn(output, variables, file, samples): stack = [] for element in output: if type(element) is Operator: num2 = stack.pop() num1 = stack.pop() evaluated = element.function(num1, num2) if samples: file.write(evaluated.getError() + "\n") stack.append(evaluated) elif type(element) is Function: count = 0 args = [] while count < element.args: args.append(stack.pop()) count += 1 if len(args) == 1: args = args[0] evaluated = element.function(args) if samples: file.write(evaluated.getError() + "\n") stack.append(evaluated) else: if element in variables: stack.append(variables.get(element)) elif element in CONSTANTS: stack.append(CONSTANTS.get(element)) else: number = Number(float(element), element) stack.append(number) return stack.pop()
def test_can_invert(self): value = Number().fromNumber(0x15) result = ~value self.assertEqual(-22, result.number) self.assertEqual("-0016", result.asHex)
def __update_region(self, region): center = region.get_center() bounds = region.get_bounds() if self.__numbers.__len__() == 0: number = Number(bounds) self.__numbers.append(number) return number distances = [] for number in self.__numbers: distances.append(vec.distance(center, number.get_center())) number = None i = np.argmin(distances) if distances[i] < 20: number = self.__numbers[i] if number is None: number = Number(bounds) self.__numbers.append(number) else: number.set_bounds(bounds) return number
def test_parse_decimal_negative_number(self): number = -1699 obj = Number().fromNumber(number) self.assertEqual(number, obj.number) self.assertEqual("-06A3", obj.asHex) self.assertEqual("-1,699", obj.asDecimal) self.assertEqual("-3243", obj.asOctal) self.assertEqual("-0110 1010 0011", obj.asBinary)
def test_parse_decimal_positve_number_string(self): string = "1699" obj = Number().fromString(string) self.assertEqual(0x6A3, obj.number) self.assertEqual("06A3", obj.asHex) self.assertEqual("1,699", obj.asDecimal) self.assertEqual("3243", obj.asOctal) self.assertEqual("0110 1010 0011", obj.asBinary)
def test_parse_decimal_negative_number_string(self): string = "-1699" obj = Number().fromString(string) self.assertEqual(-0x6A3, obj.number) self.assertEqual("-06A3", obj.asHex) self.assertEqual("-1,699", obj.asDecimal) self.assertEqual("-3243", obj.asOctal) self.assertEqual("-0110 1010 0011", obj.asBinary)
def test_parse_binary_positve_number(self): number = 0b11010100011 obj = Number().fromNumber(number) self.assertEqual(number, obj.number) self.assertEqual("06A3", obj.asHex) self.assertEqual("1,699", obj.asDecimal) self.assertEqual("3243", obj.asOctal) self.assertEqual("0110 1010 0011", obj.asBinary)
def __init__(self,x=0,y=0,z=0): if hasattr(x,'__getitem__'): self.x=x[0] self.y=x[1] self.z=x[2] elif Vector.is_vector(x): self.x=x.x self.y=x.y self.z=x.z elif Number.is_number(x) and Number.is_number(y) and Number.is_number(z): self.x=float(x) self.y=float(y) self.z=float(z) else: print("ERROR:<__init__@Vector>:Can not init.\n") exit() self.vector=(self.x,self.y,self.z)
def __mul__(self, other): if Vector.is_vector(other): x=other.x y=other.y z=other.z return self.x*x+self.y*y+self.z*z elif Number.is_number(other): return Vector(self.x*other,self.y*other,self.z*other) else: exit("ERROR:<__mul__@Vector>:Can not multiply.\n")
def powers_of_ten(): for exponent in count(): value = 10**exponent with_commas = "{:,}".format(value) yield Number( value=value, display_value=with_commas, formatted_value=with_commas, category="powers of ten", )
def __init__(self, value = None): if value == ' ': value = None if not Number.is_valid(value): raise InvalidSquareValueException('Invalid initial value for square: ' + str(value)) self._value = value self.locked = value is not None self._box = None self._row = None self._column = None self._puzzle = None
def setUp(self): self.context = FakeContext() self.sk = self.context.generate_keys() self.one = Number.from_plaintext(1, self.context, self.sk) self.two = Number.from_plaintext(2, self.context, self.sk) self.three = Number.from_plaintext(3, self.context, self.sk) self.zero = Number.from_plaintext(0, self.context, self.sk) self.two_five_four = Number.from_plaintext(254, self.context, self.sk) self.two_five_five = Number.from_plaintext(255, self.context, self.sk) utils.zero = Number.from_plaintext(0, self.context, self.sk, size=1) utils.one = Number.from_plaintext(1, self.context, self.sk, size=1)
def _check_coeff_list(maybe_coeffs): """ 引数が数値を要素とするiterableかどうかを判定する 数値のみからなる場合はtrueを、 数値以外を含む場合はfalseを返す。 数値かどうかの判定にはNumber.isnumber()を用いる """ for elm in maybe_coeffs: if not Number.isnumber(elm): return false return true
def powers_of_two(): # Start at 2^2=4 because 2^0=1 and 2^1=2 aren't interesting. for exponent in count(2): value = 2**exponent with_commas = "{:,}".format(value) yield Number( value=value, display_value="2^%s" % exponent, formatted_value=with_commas, category="powers of two", )
def checkNum( num ): """Check if given <num.value> satisfies following requirements: 1. sum(num.divisors) > num.value 2. No subset from powerset of <num.divisors> adds up to exactly <num.value> """ global pitches num = Number( num ) isOfInterest = True if sum( num.divisors ) > num.value: subsets = num.powerset() for subset in subsets: if sum( subset ) == num.value: isOfInterest = False break else: isOfInterest = False if isOfInterest: pitches.append( num.value )
""" use C++ class in Python code (c++ module + py shadow class) this script runs the same tests as the main.cxx C++ file """ from number import Number # imports .py C++ shadow class module num = Number(1) # make a C++ class object in Python num.add(4) # call its methods from Python num.display() # num saves the C++ 'this' pointer num.sub(2) num.display() res = num.square() # converted C++ int return value print('square: ', res) num.data = 99 # set C++ data member, generated __setattr__ val = num.data # get C++ data member, generated __getattr__ print('data: ', val) # returns a normal Python integer object print('data+1: ', val + 1) num.display() print(num) # runs repr in shadow/proxy class del num # runs C++ destructor automatically
from number import Number n4 = Number(4) n5 = Number(5) n1 = Number(1) n1.set_value(n4 - n5) print n1
def __floordiv__(self, other): if Number.is_number(other): return Vector(self.x//other,self.y//other,self.z//other) else: exit("ERROR:<__floordiv__@Vector>:Can not divide.\n")
def assemble(self, srcfile): self.info("Assembling %s" % srcfile, source=False) self.context.srcfile = srcfile self.context.linenum = 0 sfile = open(srcfile) lines = sfile.readlines() self.context.log(7, "assemble: file %s, lines %d" % (srcfile, len(lines))) sfile.close() for line in lines: indentError = False if line.endswith('\n'): line = line[:-1] srcline = line.expandtabs(8) self.context.srcline = srcline self.context.linenum += 1 self.context.global_linenum += 1 self.context.code = None self.context.addSymbol = True self.context.messages = [] label = None pseudolabel = None opcode = None operands = None comment = None self.context.log(7, "assemble: %s %d/%d (%d) \"%s\"" % (srcfile, self.context.linenum, len(lines), self.context.global_linenum, self.context.srcline)) if line.startswith('$'): modname = line[1:].split()[0] if not os.path.isfile(modname): self.fatal("File \"%s\" does not exist" % modname, source=False) record = self._makeNewRecord(srcline, RecordType.INCLUDE, None, None, None, None, comment) record.complete = True self.context.records.append(record) self.context.log(7, "assemble: added record %d" % (len(self.context.records) - 1)) self.assemble(modname) continue if len(line.strip()) == 0: record = self._makeNewRecord(srcline, RecordType.BLANK, None, None, None, None, None) record.complete = True self.context.records.append(record) self.context.log(7, "assemble: added record %d" % (len(self.context.records) - 1)) continue if line.strip().startswith('#'): comment = line record = self._makeNewRecord(srcline, RecordType.COMMENT, None, None, None, None, comment) record.complete = True self.context.records.append(record) self.context.log(7, "assemble: added record %d" % (len(self.context.records) - 1)) continue # Real parsing starts here. if '#' in line: comment = line[line.index('#'):] line = line[:line.index('#')] fields = line.split() if not line.startswith(' ') and not line.startswith('\t'): if line.startswith('+') or line.startswith('-'): # Check if label is [+-]number, which is a pseudo-label. checknum = fields[0][1:] checkval = Number(checknum) if checkval.isValid(): # It's a pseudo-label. pseudolabel = fields[0] if pseudolabel == None: label = fields[0] if len(fields) == 1: # Label only. self.context.symtab.add(label, None, self.context.loc, 0, RecordType.LABEL) record = self._makeNewRecord(srcline, RecordType.LABEL, label, None, None, None, comment) record.complete = True self.context.records.append(record) self.context.log(7, "assemble: added record %d" % (len(self.context.records) - 1)) continue fields = fields[1:] else: if line.strip(' ').startswith('+') or line.strip(' ').startswith('-'): # It's a pseudo-label. pseudolabel = fields[0] fields = fields[1:] try: opcode = fields[0] except: print self.context.srcfile, self.context.linenum print line print fields raise operands = " " .join(fields[1:]) if operands == "": operands = None else: operands = operands.strip().split() label_len = 0 if label != None: label_len = len(label) if opcode != None: opindex = self.context.srcline.find(opcode, label_len) elif operands != None: opindex = self.context.srcline.find(operands[0], label_len) else: opindex = -1 if opindex != -1: if opindex == 24: newoperands = [ opcode ] if operands != None: newoperands.extend(operands) if opcode not in self.context.opcodes[OpcodeType.DIRECTIVE] and \ (opcode not in self.context.opcodes[self.context.mode] or \ (opcode in self.context.opcodes[self.context.mode] and opcode != self.context.opcodes[self.context.mode][opcode].mnemonic)) or \ ((opcode == "TC" or opcode == "VN" or opcode == "MM") and operands == None): # Handle stand-alone interpretive operands. operands = newoperands opcode = None else: indentError = True self.context.log(7, "assemble: label='%s' opcode='%s' operands=%s [%d]" % (label, opcode, operands, opindex)) self.context.previousRecord = self.context.currentRecord self.context.currentRecord = self._makeNewRecord(srcline, RecordType.NONE, label, pseudolabel, opcode, operands, comment) if indentError or line.startswith('\t+') or line.startswith(' \t+') or \ line.startswith('\t-') or line.startswith(' \t-'): # It's a pseudo-label. self.context.warn("bad indentation") if opindex != -1: if opindex != 16 and opindex != 24: self.context.error("bad indentation") if opindex == 24: # TC is also used as an interpretive label. if opcode != None: self.context.warn("bad indentation") self.parse(label, opcode, operands) self.context.currentRecord.update() self.context.records.append(self.context.currentRecord) self.context.log(7, "assemble: added record %d" % (len(self.context.records) - 1))
def add(self, other): print "in Python add..." Number.add(self, other)
def add(self, other): # extend method print('in Python add...') Number.add(self, other)
from number import Number # use C++ class in Python (shadow class) # runs same tests as main.cxx C++ file num = Number(1) # make a C++ class object in Python num.add(4) # call its methods from Python num.display() # num saves the C++ 'this' pointer num.sub(2) num.display() num.data = 99 # set C++ data member, generated __setattr__ print num.data # get C++ data member, generated __getattr__ num.display() del num # runs C++ destructor automatically
from number import Number n4 = Number(4) n5 = Number(5) n1 = Number(1) n1.set_value(n4 + n5) print n1