Skip to content

Instantly share code, notes, and snippets.

@nasirovsh
Created October 4, 2020 07:32
Show Gist options
  • Save nasirovsh/57b0eb0ba75dfbf9bc9c5d904d1e9e86 to your computer and use it in GitHub Desktop.
Save nasirovsh/57b0eb0ba75dfbf9bc9c5d904d1e9e86 to your computer and use it in GitHub Desktop.

Revisions

  1. nasirovsh created this gist Oct 4, 2020.
    81 changes: 81 additions & 0 deletions miso_test_1
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,81 @@
    import sys


    class Solution:
    def __init__(self):
    self.w2n_map = {str(n): n for n in range(10)}

    def read_input(self, argv):
    if len(argv) < 2:
    return None, None
    a = argv[0]
    b = argv[1]
    return a, b

    def word_to_num(self, num_str):
    return self.w2n_map.get(num_str)

    def add_nums(self, a, b):
    a_len, b_len = len(a), len(b)
    a, b = a[::-1], b[::-1]
    if a_len >= b_len:
    bigger, smaller = a, b
    else:
    bigger, smaller = b, a
    result = []
    carry = None
    for i, d in enumerate(bigger):
    k = (self.word_to_num(smaller[i]) if i < len(smaller) else 0)
    m = self.word_to_num(bigger[i])
    s = k + m # add integers
    if carry:
    s += carry
    carry = None
    if s >= 10:
    carry = 1
    s = s % 10
    result.append(str(s))
    if carry:
    result.append(str(carry))

    return ''.join(result[::-1])


    def main(argv):
    solution = Solution()
    a, b = solution.read_input(argv)
    if not a or not b: # empty string
    return
    sum_out = solution.add_nums(a, b)
    print("{}".format(sum_out))


    def tests():
    solution = Solution()

    test_ins, test_outs = [], []
    a, b, r = '357', '58', '415'
    test_ins.append((a, b))
    test_outs.append(r)
    a, b, r = '36243570', '34563658', '70807228'
    test_ins.append((a, b))
    test_outs.append(r)
    a, b, r = '10000', '500000', '510000'
    test_ins.append((a, b))
    test_outs.append(r)
    a, b, r = '9999', '1', '10000'
    test_ins.append((a, b))
    test_outs.append(r)
    a, b, r = '1010101', '90909', '1101010'
    test_ins.append((a, b))
    test_outs.append(r)

    for i, test_in in enumerate(test_ins):
    a, b = test_in[0], test_in[1]
    result_sum = solution.add_nums(a, b)
    # print(type(result_sum))
    print("{} + {} = {} ; should be {}".format(a, b, result_sum, test_outs[i]))


    if __name__ == "__main__":
    main(sys.argv[1:])