-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathadd_two_numbers_list.py
106 lines (76 loc) · 2.44 KB
/
add_two_numbers_list.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
def zip_longest_linked_lists(a, b):
default = ListNode(0)
while a or b:
if a and b:
yield a, b
a = a.next
b = b.next
elif a:
yield a, default
a = a.next
elif b:
yield default, b
b = b.next
def add_numbers(term_a, term_b):
results = AdditionLinkedList()
for node_a, node_b in zip_longest_linked_lists(term_a, term_b):
results.add(node_a, node_b)
results.add_carryover()
return results.head
class AdditionLinkedList():
def __init__(self):
self.head = None
self.tail = self.head
self.carryover = 0
def add(self, term_a, term_b):
result = term_a.val + term_b.val + self.carryover
self.carryover = result / 10
digit = result % 10
new_node = ListNode(digit)
self.append(new_node)
def add_carryover(self):
if self.carryover > 0:
self.append(ListNode(self.carryover))
self.carryover = 0
def append(self, new_node):
if self.tail:
self.tail.next = new_node
self.tail = self.tail.next
else:
self.head = new_node
self.tail = self.head
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __eq__(self, other):
return self.val == other.val and self.next == other.next
def __repr__(self):
return '<Node {} {}>'.format(self.val, self.next)
class LinkedList(ListNode):
def __init__(self, arr):
nodes = [ListNode(v) for v in arr]
for i in range(1, len(nodes)):
nodes[i-1].next = nodes[i]
head = nodes[0]
self.val = head.val
self.next = head.next
def test_simple_addition():
a = LinkedList([2, 4, 3])
b = LinkedList([3, 5, 2])
assert add_numbers(a, b) == LinkedList([5, 9, 5])
def test_addition_carryover():
a = LinkedList([2, 4, 3])
b = LinkedList([5, 6, 4])
assert add_numbers(a, b) == LinkedList([7, 0, 8])
def test_addition_multi_carryover():
a = LinkedList([9, 3, 5])
b = LinkedList([2, 8, 9])
assert add_numbers(a, b) == LinkedList([1, 2, 5, 1])
def test_add_unequal_numbers():
a = LinkedList([9, 9, 1])
b = LinkedList([1])
assert add_numbers(a, b) == LinkedList([0, 0, 2])
c = LinkedList([1, 5])
d = LinkedList([5, 5, 9, 9])
assert add_numbers(c, d) == LinkedList([6, 0, 0, 0, 1])