Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.6 kB
3
Indexable
Never
from module import LongInt

def main():
    # instantiate two LongInt objects
    first = LongInt('0')
    second = LongInt('0')

    # initialize input objects
    try:
        file = open('LongInts.txt', 'r')
        lines = file.readlines()
        file.close()

        for i in range(0, len(lines), 2):
            try:
                line1 = lines[i].strip()
                line2 = lines[i + 1].strip()

                first = LongInt(line1)
                second = LongInt(line2)

                # perform the arithmetic
                result = first.add_num(second)

                # display the results
                first.print_longint()
                second.print_longint()
                print("-" * 21)
                result.print_longint()
                print("\n")
            except ValueError as e:
                print(e)
                continue
    except IOError:
        print("Error: Unable to read the file.")


if __name__ == "__main__":
    main()

#eggs


class LongInt:
    def __init__(self, number_str, has_carry=False):
        try:
            self.numbers = self.parse_number_str(number_str)
            self.has_carry = has_carry
        except ValueError:
            raise ValueError(f"{number_str} is invalid, skipping...\n")

    def parse_number_str(self, number_str):
        if len(number_str) < 20:
            number_str = '0' * (20 - len(number_str)) + number_str
        return [int(digit) for digit in number_str]

    def add_num(self, other):
        result = []
        carry_bit = False

        for i in range(19, -1, -1):
            digit_sum = self.numbers[i] + other.numbers[i]

            if carry_bit:
                digit_sum += 1

            if digit_sum > 9:
                carry_bit = True
                digit_sum %= 10
            else:
                carry_bit = False

            result.insert(0, digit_sum)

        return LongInt(''.join(map(str, result)), carry_bit)

    def print_longint(self):
        should_check = True

        if self.has_carry:
            print(1, end='')
        elif self.numbers.count(0) == len(self.numbers):
            print(' ' * 19, 0)
            return
        else:
            print(end=' ')

        for digit in self.numbers:
            if should_check and digit == 0 and not self.has_carry:
                digit = ' '
            else:
                should_check = False

            print(digit, end='')
        print()