Beispiel #1
0
class Const:
    def __init__(self):
        self.digit = None
        self.const = None
        self.name = ''

    #Simple recursive parsing to build what value the const has, based on the string passed in
    def parse(self, constStr):
        length = len(constStr)
        if length <= 1:
            self.digit = Digit()
            self.digit.parse(constStr)
            self.name = self.digit.dig
        else:
            self.const = Const()
            self.const.parse(constStr[0:length - 1])
            self.digit = Digit()
            self.digit.parse(constStr[length - 1])
            self.name = self.const.name + self.digit.dig

    #Simple print
    def print(self):
        print(int(self.name), end='')

    #Simple execution that returns the value of the const
    def exec(self):
        return int(self.name)
Beispiel #2
0
 def parse(self, constStr):
     length = len(constStr)
     if length <= 1:
         self.digit = Digit()
         self.digit.parse(constStr)
         self.name = self.digit.dig
     else:
         self.const = Const()
         self.const.parse(constStr[0:length - 1])
         self.digit = Digit()
         self.digit.parse(constStr[length - 1])
         self.name = self.const.name + self.digit.dig
Beispiel #3
0
    def __setitem__(self: FractionalNumber, key: int,
                    value: Union[Digit, int]) -> None:
        if key >= len(self.digits):
            excess = key - len(self.digits) + 1
            self.digits[0:0] = [Digit(0)] * excess  # insert at 0
        if isinstance(value, int):
            self.digits[len(self.digits) - key - 1] = Digit(value)
        elif isinstance(value, Digit):
            self.digits[len(self.digits) - key - 1] = value
        else:
            raise Exception()

        self._prune_unnecessary_0s()
Beispiel #4
0
    def __setitem__(self: WholeNumber, key: int, value: Union[Digit,
                                                              int]) -> None:
        if key >= len(self.digits):
            excess = key - len(self.digits) + 1
            self.digits.extend([Digit(0)] * excess)
        if isinstance(value, int):
            self.digits[key] = Digit(value)
        elif isinstance(value, Digit):
            self.digits[key] = value
        else:
            raise Exception()

        self._prune_unnecessary_0s()
Beispiel #5
0
    def will_division_terminate(lhs: DecimalNumber,
                                rhs: DecimalNumber) -> bool:
        log(f'Checking if {lhs} / {rhs} results in a non-terminating decimal...'
            )
        log_indent()

        adjust_len_self = len(lhs.fractional.digits)
        adjust_len_other = len(rhs.fractional.digits)

        log(f'Generating mock integer number for {lhs}...')
        lhs_extra_0s = adjust_len_self - len(lhs.fractional.digits)
        lhs_combined_digits = lhs.fractional.digits + lhs.whole.digits
        lhs_combined_digits[0:0] = [Digit(0)] * lhs_extra_0s
        mock_self = IntegerNumber(lhs.sign, WholeNumber(lhs_combined_digits))
        log(f'{mock_self}')

        log(f'Generating mock integer number for {rhs}...')
        rhs_extra_0s = adjust_len_other - len(rhs.fractional.digits)
        rhs_combined_digits = rhs.fractional.digits + rhs.whole.digits
        rhs_combined_digits[0:0] = [Digit(0)] * rhs_extra_0s
        mock_other = IntegerNumber(rhs.sign, WholeNumber(rhs_combined_digits))
        log(f'{mock_other}')

        log(f'Generating mock fraction for {lhs} / {rhs}...')
        mock_fraction = FractionNumber(mock_self, mock_other)
        log(f'{mock_fraction}')

        log(f'Simplifying mock fraction...')
        mock_fraction = mock_fraction.simplify()
        log(f'{mock_fraction}')

        log(f'Checking if prime factors of denom ({mock_fraction.denominator}) is {{}}, {{2}}, {{5}}, or {{2,5}}...'
            )
        mock_fraction_denom_prime_factors = set(
            factor_tree(mock_fraction.denominator).get_prime_factors())
        if not (
            {WholeNumber.from_str('2'),
             WholeNumber.from_str('5')} == mock_fraction_denom_prime_factors or
            {WholeNumber.from_str('2')} == mock_fraction_denom_prime_factors or
            {WholeNumber.from_str('5')} == mock_fraction_denom_prime_factors
                or 0 == len(mock_fraction_denom_prime_factors)):
            ret = False
            log(f'{ret} -- Won\'t terminate.')
        else:
            ret = True
            log(f'{ret} -- Will terminate.')

        log_unindent()
        log(f'{ret}')
        return ret
Beispiel #6
0
class Id:
    def __init__(self):
        self.letter = None
        self.id = None
        self.digit = None
        self.name = ''

    #Recursive parsing to determine what combination of letters and digits the id is made up of based on string passed in.
    #This builds the name for the id
    def parse(self, idStr):
        length = len(idStr)
        if length <= 1:
            self.letter = Letter()
            self.letter.parse(idStr)
            self.name = self.letter.let
        elif idStr[length - 1].isalpha:
            self.letter = Letter()
            self.letter.parse(idStr[length - 1])
            self.id = Id()
            self.id.parse(idStr[0:length - 1])
            self.name = self.id.name + self.letter.let
        elif idStr[length - 1].isnumeric():
            self.digit = Digit()
            self.digit.parse(idStr[length - 1])
            self.id = Id()
            self.id.parse(idStr[0:length - 1])
            self.name = self.id.name + self.digit.dig

    #Simple print
    def print(self):
        print(self.name, end='')

    #Used for determining value of the id
    def exec(self):
        return self.getValue()

    #Sets the value and checks if the variable was ever even initialized
    def setValue(self, val):
        if TokList.getIdValue(self.name) is None:
            print('ERROR: Value not initialized')
        TokList.setIdValue(self.name, val)

    #Gets value of the variable and checks to see if it was even initialized or even given a value
    def getValue(self):
        if TokList.getIdValue(
                self.name) == 'null' or TokList.getIdValue(self.name) is None:
            print('ERROR: Value undeclared')
            exit()
        return int(TokList.getIdValue(self.name))
def ParseXMLFile(xmlFileName):
    xmlDoc = ET.parse(xmlFileName)
    rootNode = xmlDoc.getroot()
    idSpeaker = rootNode.find('IdSpeaker').text
    idSession = rootNode.find('IdSession').text
    device = rootNode.find('Device').text
    typeSequence = rootNode.find('TypeSequence').text
    digits = rootNode.find('Digits').text
    digits = digits.split()

    digitsById = []
    for i in range(11):
        digitNode = rootNode.find('digit' + str(i + 1))
        if not digitNode:
            break
        digitName = digits[i]
        digitId = digitsByName[digitName]
        startDigit = digitNode.find('start_digit').text
        endDigit = digitNode.find('end_digit').text
        startTightDigit = digitNode.find('start_tight_digit').text
        endTightDigit = digitNode.find('end_tight_digit').text
        digit = Digit(digitId, startDigit, endDigit, startTightDigit,
                      endTightDigit, digitName)
        digitsById.append(digit)

    sequence = Sequence(idSpeaker, idSession, device, typeSequence, digitsById)
    return sequence
Beispiel #8
0
 def from_int(value: int) -> WholeNumber:
     if value < 0:
         raise Exception('Negative int not allowed')
     digits = str(value)
     digits = list(map(lambda i: Digit(int(i)), digits))
     digits.reverse()
     return WholeNumber(digits)
Beispiel #9
0
def select_roi(image_bin):

    _, contours, _ = cv2.findContours(image_bin.copy(), cv2.RETR_EXTERNAL,
                                      cv2.CHAIN_APPROX_SIMPLE)

    regions = []

    for i in range(0, len(contours)):
        contour = contours[i]
        x = cv2.boundingRect(contour)[0]
        y = cv2.boundingRect(contour)[1]
        w = cv2.boundingRect(contour)[2]
        h = cv2.boundingRect(contour)[3]
        if h > 10:  #ako je visina veca od 10
            existingDigit = exist(cv2.boundingRect(contour))
            if existingDigit is None:
                digit = Digit(x, y, w, h, False, None)
                global digitArray
                digitArray.append(digit)
            else:
                existingDigit.x = x
                existingDigit.y = y
                existingDigit.w = w
                existingDigit.h = h
            # kopirati [y:y+h+1, x:x+w+1] sa binarne slike i smestiti u novu sliku
            region = image_bin[y:y + h, x:x + w]
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
            regions.append(resize_region(region))

    return regions
Beispiel #10
0
 def __init__(self, home_color, away_color):
     self.led_values = []
     self.hyphen_color_value = color_name_to_rgb_tuple['purple']
     self.home_color_value = color_name_to_rgb_tuple[home_color]
     self.away_color_value = color_name_to_rgb_tuple[away_color]
     self.digits = []
     self.reset_led_values()
     for i in range(4):
         self.digits.append(Digit(i))
Beispiel #11
0
 def parse(self, idStr):
     length = len(idStr)
     if length <= 1:
         self.letter = Letter()
         self.letter.parse(idStr)
         self.name = self.letter.let
     elif idStr[length - 1].isalpha:
         self.letter = Letter()
         self.letter.parse(idStr[length - 1])
         self.id = Id()
         self.id.parse(idStr[0:length - 1])
         self.name = self.id.name + self.letter.let
     elif idStr[length - 1].isnumeric():
         self.digit = Digit()
         self.digit.parse(idStr[length - 1])
         self.id = Id()
         self.id.parse(idStr[0:length - 1])
         self.name = self.id.name + self.digit.dig
Beispiel #12
0
def main():
    zeroTraining, zeroTrainingLengths, zeroTest, zeroTestLength, zeroTestLines = load_data(r"F:\MLDM\2nd Semester\Done_ML\Practical 2\digit_strings\0.txt")
    oneTraining, oneTrainingLengths, oneTest, oneTestLength, oneTestLines = load_data(r"F:\MLDM\2nd Semester\Done_ML\Practical 2\digit_strings\1.txt")
    twoTraining, twoTrainingLengths, twoTest, twoTestLength, twoTestLines = load_data(r"F:\MLDM\2nd Semester\Done_ML\Practical 2\digit_strings\2.txt")
    threeTraining, threeTrainingLengths, threeTest, threeTestLength, threeTestLines = load_data(r"F:\MLDM\2nd Semester\Done_ML\Practical 2\digit_strings\3.txt")
    fourTraining, fourTrainingLengths, fourTest, fourTestLength, fourTestLines = load_data(r"F:\MLDM\2nd Semester\Done_ML\Practical 2\digit_strings\4.txt")
    fiveTraining, fiveTrainingLengths, fiveTest, fiveTestLength, fiveTestLines = load_data(r"F:\MLDM\2nd Semester\Done_ML\Practical 2\digit_strings\5.txt")
    sixTraining, sixTrainingLengths, sixTest, sixTestLength, sixTestLines = load_data(r"F:\MLDM\2nd Semester\Done_ML\Practical 2\digit_strings\6.txt")
    sevenTraining, sevenTrainingLengths, sevenTest, sevenTestLength, sevenTestLines = load_data(r"F:\MLDM\2nd Semester\Done_ML\Practical 2\digit_strings\7.txt")
    eightTraining, eightTrainingLengths, eightTest, eightTestLength, eightTestLines = load_data(r"F:\MLDM\2nd Semester\Done_ML\Practical 2\digit_strings\8.txt")
    nineTraining, nineTrainingLengths, nineTest, nineTestLength, nineTestLines = load_data(r"F:\MLDM\2nd Semester\Done_ML\Practical 2\digit_strings\9.txt")
    numberZeroModel = Digit(name="Zero", n_states = 12)
    numberOneModel = Digit(name="One", n_states = 18)
    numberTwoModel = Digit(name="Two", n_states = 12)
    numberThreeModel = Digit(name="Three", n_states = 12)
    numberFourModel = Digit(name="Four", n_states = 13)
    numberFiveModel = Digit(name="Five", n_states = 12)
    numberSixModel = Digit(name="Six", n_states = 10)
    numberSevenModel = Digit(name="Seven", n_states = 8)
    numberEightModel = Digit(name="Eight", n_states = 15)
    numberNineModel = Digit(name="Nine", n_states = 13)

    models = [numberZeroModel, numberOneModel, numberTwoModel, numberThreeModel, numberFourModel, numberFiveModel, numberSixModel, numberSevenModel, numberEightModel, numberNineModel ]
    testSets = [zeroTestLines, oneTestLines, twoTestLines, threeTestLines, fourTestLines, fiveTestLines, sixTestLines, sevenTestLines, eightTestLines, nineTestLines]
    num_alltestCase = 0
    num_correctly_classified = 0
    for digitTestSet in range(0, len(testSets)):
        for testCase in testSets[digitTestSet]:
            num_alltestCase = num_alltestCase + 1
            maxProb = -np.inf
            maxModel = -1
            for i in range(0, len(models)):
                prob = models[i].prob(testCase, [len(testCase)])
                if prob > maxProb:
                    maxProb = prob
                    maxModel = i
            if maxModel == digitTestSet:
                num_correctly_classified = num_correctly_classified + 1


        print("Correct: ", num_correctly_classified, " out of: ", num_alltestCase)
        ratio = (num_correctly_classified / num_alltestCase)
        print("Total accuracy: ", ratio * 100, "% ")
Beispiel #13
0
    def __mul__(lhs: DecimalNumber, rhs: DecimalNumber) -> DecimalNumber:
        log(f'Multiplying {lhs} and {rhs}...')
        log_indent()

        adjust_len_self = len(lhs.fractional.digits)
        adjust_len_other = len(rhs.fractional.digits)

        log(f'Generating mock integer number for {lhs}...')
        lhs_extra_0s = adjust_len_self - len(lhs.fractional.digits)
        lhs_combined_digits = lhs.fractional.digits + lhs.whole.digits
        lhs_combined_digits[0:0] = [Digit(0)] * lhs_extra_0s
        mock_self = IntegerNumber(lhs.sign, WholeNumber(lhs_combined_digits))
        log(f'{mock_self}')

        log(f'Generating mock integer number for {rhs}...')
        rhs_extra_0s = adjust_len_other - len(rhs.fractional.digits)
        rhs_combined_digits = rhs.fractional.digits + rhs.whole.digits
        rhs_combined_digits[0:0] = [Digit(0)] * rhs_extra_0s
        mock_other = IntegerNumber(rhs.sign, WholeNumber(rhs_combined_digits))
        log(f'{mock_other}')

        log(f'Performing {mock_self} * {mock_other}...')
        mock_ret = mock_self * mock_other
        log(f'{mock_ret}')

        log(f'Unmocking {mock_ret} back to decimal...')
        unadjust_len = adjust_len_self + adjust_len_other
        ret_sign = mock_ret.sign
        ret_fractional_digits = [
            mock_ret.magnitude[i] for i in range(0, unadjust_len)
        ]
        ret_whole_digits = [
            mock_ret.magnitude[i]
            for i in range(unadjust_len, len(mock_ret.magnitude.digits))
        ]
        ret = DecimalNumber(ret_sign, WholeNumber(ret_whole_digits),
                            FractionalNumber(ret_fractional_digits))
        log(f'{ret}')

        log_unindent()
        log(f'{ret}')

        return ret
Beispiel #14
0
    def __init__(self, digits: List[Digit]):
        if digits is None:
            self.digits = [Digit(0)]
        elif isinstance(digits, Digit):
            self.digits = [digits]
        elif isinstance(digits, list):
            self.digits = list(
                map(lambda i: Digit(i) if isinstance(i, int) else i, digits))
        elif isinstance(digits, str):
            self.digits = list(map(lambda i: Digit(int(i)), digits))
            self.digits.reverse()
        elif isinstance(digits, int):
            if digits < 0:
                raise Exception('Negative int not allowed')
            digits = str(digits)
            self.digits = list(map(lambda i: Digit(int(i)), digits))
            self.digits.reverse()
        else:
            raise Exception()

        self._prune_unnecessary_0s()
Beispiel #15
0
    def _prune_unnecessary_0s(self: FractionalNumber) -> None:
        trim_count = 0
        for digit in self.digits:
            if digit == 0:
                trim_count += 1
            else:
                break

        self.digits = self.digits[trim_count:]

        # if empty, keep a single digit there
        if len(self.digits) == 0:
            self.digits = [Digit(0)]
Beispiel #16
0
    def _prune_unnecessary_0s(self: WholeNumber) -> None:
        trim_count = 0
        for digit in reversed(self.digits):
            if digit == 0:
                trim_count += 1
            else:
                break

        self.digits = self.digits[:len(self.digits) - trim_count]

        # if empty, keep a single digit there
        if len(self.digits) == 0:
            self.digits = [Digit(0)]
Beispiel #17
0
    def _highlight(self: WholeNumber, *idxes: int) -> None:
        digits_copy = self.digits[:]

        max_idxes = max(idxes)
        if max_idxes >= len(digits_copy):
            excess = max_idxes - len(digits_copy) + 1
            digits_copy.extend([Digit(0)] * excess)

        output_str = ''
        for i in range(0, len(digits_copy)):
            dout = str(digits_copy[i].value)
            output_str = ('[' + dout +
                          ']' if i in idxes else dout) + ' ' + output_str
        return output_str
Beispiel #18
0
 def __init__(self, home_color, away_color):
     self.led_values = []
     self.score_hyphen_color_value = color_name_to_rgb_tuple['purple']
     self.home_color_value = color_name_to_rgb_tuple[home_color]
     self.away_color_value = color_name_to_rgb_tuple[away_color]
     self.hour_color_value = color_name_to_rgb_tuple['purple']
     self.minute_color_value = color_name_to_rgb_tuple['purple']
     self.clock_hyphen_color_value = color_name_to_rgb_tuple['purple']
     self.char_color_value = color_name_to_rgb_tuple['white']
     self.char_hyphen_color_value = color_name_to_rgb_tuple['black']
     self.digits = []
     self.reset_led_values(self.score_hyphen_color_value)
     for i in range(4):
         self.digits.append(Digit(i))
Beispiel #19
0
def main():
    # Usage
    print(usage())
    # Main loop
    while True:
        # Input
        user_input = str(input("Input: "))

        # Verify input with regex
        if not re.match("^(([1-9]|10),[0-9]+|0,0)$", user_input):
            # Wrong input format
            print(wrongInput(user_input))
        elif not user_input == "0,0":
            # Right input
            size, digits = user_input.split(",")

            # Preparing for output
            output = ["" for line in range(int(size) * 2 + 3)]

            # Dealing with each digit individually
            for digit in digits:
                # Instancing Digit class
                digit_to_print = Digit(int(size), int(digit))

                # Adding Digit in LCD format to output array
                for line_index in range(len(output)):
                    output[line_index] += digit_to_print.lcdNumber()[line_index] + " "

            # Showing all lines
            for line in output:
                # Removing that last " "
                print(line[:-1])
        else:
            # 0,0
            # End of program
            print("Thanks for using this software")
            break
Beispiel #20
0
def get_handwritten_matrix(matrix):
    img = Image.new('RGB', (2100, 1000), 'white')
    cursorX = 0
    cursorY = 0

    offsetX = 200
    offsetY = 100

    for i in range(0, len(matrix)):
        row = matrix[i]
        for num in row:
            temp = DigitBuilder.get_number(int(num))
            img.paste(temp, (cursorX, cursorY))
            cursorX += offsetX
        cursorX = 0
        cursorY += offsetY

    return img
Beispiel #21
0
    def from_fraction(value: FractionNumber) -> DecimalNumber:
        log(f'Converting {value} to a decimal number...')
        log_indent()

        log(f'Converting {value} to suitable fraction...')
        value = DecimalNumber.to_suitable_fraction(value)
        log(f'{value}')

        num = value.numerator
        denom = value.denominator
        if not str(denom).startswith('1'):
            raise Exception('Denominator must be power of 10')
        elif not set(str(denom)[1:]) == set('0') and not set(
                str(denom)[1:]) == set():
            raise Exception('Denominator must be power of 10')

        log(f'Resolving fraction {value}...')
        whole, remaining = num / denom
        log(f'{whole} wholes and {remaining} remaining')

        log(f'Converting {remaining} of {denom} to fractional value...')
        num_digits_in_rem = len(remaining.digits)
        num_0s_in_den = len(
            denom.digits
        ) - 1  # starts with 1 followed by 0s, so - 1 to ignore the starting 1
        num_0s_to_prepend_to_rem = num_0s_in_den - num_digits_in_rem
        fractional_digits = remaining.digits[:]  # copy digits
        fractional_digits = fractional_digits + [Digit(
            0)] * num_0s_to_prepend_to_rem  # this prepending 0s...
        # you might be confused because the
        # 0s are being addeed to the end, but
        # that's how FractionalNumber expects
        # digits -- in reversed order
        fractional = FractionalNumber(fractional_digits)
        log(f'{fractional}')

        sign = value.sign

        log_unindent()

        ret = DecimalNumber(sign, whole, fractional)
        log(f'Decimal number: {ret}')
        return ret
Beispiel #22
0
def read(imagefile, labelfile, n):
    i = open(imagefile, 'rb')
    l = open(labelfile, 'rb')
    i.read(4)  # magic 1
    i.read(4)  # numImages
    i.read(4)  # numRows
    i.read(4)  # numCols

    l.read(4)  # magic 2
    l.read(4)  # numImages

    images = []

    for k in range(0, n):
        image = Image.new('L', (28, 28))
        image.putdata(i.read(784))

        m = numpy.matrix(list(chunks(list(image.getdata()), 28)))

        d = Digit(image, m, int.from_bytes(l.read(1), byteorder='big'))

        images.append(d)

    return images
Beispiel #23
0
 def shift_left(self: WholeNumber, count: int) -> None:
     for i in range(0, count):
         self.digits.insert(0, Digit(0))
     self._prune_unnecessary_0s()
Beispiel #24
0
 def _as_digit(self: WholeNumber) -> Digit:
     return Digit(int(str(self)), allowOob=True)
Beispiel #25
0
    def to_words(self: WholeNumber) -> str:
        suffixes = [
            None, 'thousand', 'million', 'billion', 'trillion', 'quadrillion',
            'quintillion'
        ]

        log(f'Converting {self}...')
        log_indent()

        output = ''

        digits_copy = self.digits[:]
        while not digits_copy == []:
            d1 = digits_copy.pop(0) if digits_copy != [] else None
            d2 = digits_copy.pop(0) if digits_copy != [] else None
            d3 = digits_copy.pop(0) if digits_copy != [] else None

            log(f'Converting group {d3} {d2} {d1}...')
            log_indent()

            txt = ''
            if d3 is not None and d3 != Digit(0):
                if d3.value == Digit(1):
                    txt += 'one hundred'
                elif d3.value == Digit(2):
                    txt += 'two hundred'
                elif d3.value == Digit(3):
                    txt += 'three hundred'
                elif d3.value == Digit(4):
                    txt += 'four hundred'
                elif d3.value == Digit(5):
                    txt += 'five hundred'
                elif d3.value == Digit(6):
                    txt += 'six hundred'
                elif d3.value == Digit(7):
                    txt += 'seven hundred'
                elif d3.value == Digit(8):
                    txt += 'eight hundred'
                elif d3.value == Digit(9):
                    txt += 'nine hundred'
                else:
                    raise Exception()

            ignore_first_digit = False
            if d2 is not None and d3 != Digit(0):
                txt += ' '
                if d2.value == Digit(1):
                    ignore_first_digit = True
                    if d1 == Digit(0):
                        txt += 'ten'
                    elif d1 == Digit(1):
                        txt += 'eleven'
                    elif d1 == Digit(2):
                        txt += 'twelve'
                    elif d1 == Digit(3):
                        txt += 'thirteen'
                    elif d1 == Digit(4):
                        txt += 'fourteen'
                    elif d1 == Digit(5):
                        txt += 'fifteen'
                    elif d1 == Digit(6):
                        txt += 'sixteen'
                    elif d1 == Digit(7):
                        txt += 'seventeen'
                    elif d1 == Digit(8):
                        txt += 'eighteen'
                    elif d1 == Digit(9):
                        txt += 'nineteen'
                    else:
                        raise Exception()
                elif d2.value == Digit(2):
                    txt += 'twenty'
                elif d2.value == Digit(3):
                    txt += 'thirty'
                elif d2.value == Digit(4):
                    txt += 'forty'
                elif d2.value == Digit(5):
                    txt += 'fifty'
                elif d2.value == Digit(6):
                    txt += 'sixty'
                elif d2.value == Digit(7):
                    txt += 'seventy'
                elif d2.value == Digit(8):
                    txt += 'eighty'
                elif d2.value == Digit(9):
                    txt += 'ninety'
                else:
                    raise Exception()

            if not ignore_first_digit and d1 is not None and d1 != Digit(0):
                txt += ' '
                if d1.value == Digit(1):
                    txt += 'one'
                elif d1.value == Digit(2):
                    txt += 'two'
                elif d1.value == Digit(3):
                    txt += 'three'
                elif d1.value == Digit(4):
                    txt += 'four'
                elif d1.value == Digit(5):
                    txt += 'five'
                elif d1.value == Digit(6):
                    txt += 'six'
                elif d1.value == Digit(7):
                    txt += 'seven'
                elif d1.value == Digit(8):
                    txt += 'eight'
                elif d1.value == Digit(9):
                    txt += 'nine'
                else:
                    raise Exception()

            if suffixes == []:
                raise Exception('Number too large')

            log(f'Words: {txt}')

            suffix = suffixes.pop(0)
            if suffix is not None:
                txt += ' ' + suffix

            log(f'Suffix: {suffix}')
            log_unindent()

            output = txt + ' ' + output

        output = output.lstrip()
        if output == '':
            output = 'zero'

        log_unindent()
        log(f'{output}')

        return output.strip()
Beispiel #26
0
 def __getitem__(self: WholeNumber, key: int) -> Digit:
     if key >= len(self.digits):
         return Digit(0)
     return self.digits[key]
Beispiel #27
0
 def from_int_list(digits: List[int]) -> WholeNumber:
     digits = list(map(lambda i: Digit(i), digits))
     return WholeNumber(digits)
Beispiel #28
0
    def round(self: DecimalNumber, position: str) -> DecimalNumber:
        log(f'Rounding {self} at {position} position...')
        log_indent()

        position = position.strip()
        if position.endswith('s'):
            position = position[:-1]
        position_word_to_index = {
            'hundred-quintillion': 20,
            'ten-quintillion': 19,
            'quintillion': 18,
            'hundred-quadillion': 17,
            'ten-quadrillion': 16,
            'quadrillion': 15,
            'hundred-trillion': 14,
            'ten-trillion': 13,
            'trillion': 12,
            'hundred-billion': 11,
            'ten-billion': 10,
            'billion': 9,
            'hundred-million': 8,
            'ten-million': 7,
            'million': 6,
            'hundred-thousand': 5,
            'ten-thousand': 4,
            'thousand': 3,
            'hundred': 2,
            'ten': 1,
            'one': 0,
            'tenth': -1,
            'hundredth': -2,
            'thousandth': -3,
            'ten-thousandth': -4,
            'hundred-thousandth': -5,
            'millionth': -6,
            'ten-millionth': -7,
            'hundred-millionth': -8,
            'billionth': -9,
            'ten-billionth': -10,
            'hundred-billionth': -11,
            'trillionth': -12,
            'ten-trillionth': -13,
            'hundred-trillionth': -14,
            'quadrillionth': -15,
            'ten-quadrillionth': -16,
            'hundred-quadillionth': -17,
            'quintillionth': -18,
            'ten-quintillionth': -19,
            'hundred-quintillionth': -20,
        }
        position_idx = position_word_to_index[position]
        if position_idx is None:
            raise Exception('Position unknown')

        next_position_idx = position_idx - 1

        log(f'Determining adder based on following position...')
        log_indent()
        log(f'Checking if digit at following position is >= 5...')
        following_digit = WholeNumber.from_digit(self[next_position_idx])
        if following_digit >= WholeNumber.from_str("5"):
            log(f'True ({following_digit} >= 5), deriving adder based on position...'
                )
            if position_idx >= 0:
                adder = DecimalNumber(
                    self.sign, WholeNumber.from_str('1' + '0' * position_idx),
                    FractionalNumber.from_str('0'))
            else:
                adder = DecimalNumber(
                    self.sign, WholeNumber.from_str('0'),
                    FractionalNumber.from_str('0' * -(position_idx + 1) + '1'))
        else:
            log(f'False ({following_digit} < 5), setting adder to 0...')
            adder = DecimalNumber.from_str('0')
        log_unindent()
        log(f'{adder}')

        log(f'Adding {adder} to {self}...')
        ret = self.copy() + adder
        log(f'{ret}')

        log(f'Truncating all following positions...')
        log_indent()
        if position_idx >= 0:
            for i in range(0, position_idx):
                ret[i] = Digit(0)
                log(f'{ret}')
            for i in range(0, len(self.fractional.digits)):
                ret[-i - 1] = Digit(0)
                log(f'{ret}')
        else:
            for i in range(-position_idx, len(self.fractional.digits)):
                ret[-i - 1] = Digit(0)
                log(f'{ret}')
        log_unindent()
        log(f'{ret}')

        log_unindent()
        log(f'{ret}')

        return ret
Beispiel #29
0
 def setUp(self):
     self.unidigit = Digit(ingest=True, unique=False)
Beispiel #30
0
 def from_str(digits: str) -> WholeNumber:
     digits = list(map(lambda i: Digit(int(i)), digits))
     digits.reverse()
     return WholeNumber(digits)