Skip to content

Commit 79f40d9

Browse files
committed
remove precondition, update sum_lists code
1 parent d18d781 commit 79f40d9

File tree

1 file changed

+29
-4
lines changed

1 file changed

+29
-4
lines changed

Python/chapter02/2.5 - Sum Lists/miguel_2.5_soln.py

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,6 @@ def sum_lists(ll1: LinkedList, ll2: LinkedList) -> LinkedList:
181181
"""
182182
Will add ll1 and ll2 where each element in the linked lists
183183
represent digits.
184-
Precondition: ll1 and ll2 must be the same length.
185184
Digits are in backward order, for example:
186185
Input: (7 -> 1 -> 6) + (5 -> 9 -> 2). That is, 617 + 295
187186
Result: 2 -> 1 -> 9. That is, 912
@@ -191,9 +190,9 @@ def sum_lists(ll1: LinkedList, ll2: LinkedList) -> LinkedList:
191190
:param ll2: second input linked list
192191
:return: a linked list containing the result of the addition
193192
"""
194-
assert(ll1.size == ll2.size)
195-
n1 = ll1.head
196-
n2 = ll2.head
193+
shorter_ll, longer_ll = (ll1, ll2) if ll1.size < ll2.size else (ll2, ll1)
194+
n1 = shorter_ll.head
195+
n2 = longer_ll.head
197196
output_ll = LinkedList()
198197
carry = 0
199198
while n1 is not None:
@@ -208,6 +207,17 @@ def sum_lists(ll1: LinkedList, ll2: LinkedList) -> LinkedList:
208207
output_ll.append_to_tail(result)
209208
n1 = n1.next
210209
n2 = n2.next
210+
# loop through remaining longer list
211+
while n2 is not None:
212+
value = n2.data
213+
result = value + carry
214+
if result >= 10:
215+
carry = 1
216+
result -= 10
217+
else:
218+
carry = 0
219+
output_ll.append_to_tail(result)
220+
n2 = n2.next
211221
if carry > 0:
212222
output_ll.append_to_tail(carry)
213223
return output_ll
@@ -246,6 +256,21 @@ def setUp(self):
246256
LinkedList(9, 9, 9, 9),
247257
LinkedList(9, 9, 9, 9),
248258
LinkedList(8, 9, 9, 9, 1)
259+
),
260+
(
261+
LinkedList(9, 9, 9, 9),
262+
LinkedList(9, 9),
263+
LinkedList(8, 9, 0, 0, 1)
264+
),
265+
(
266+
LinkedList(1, 2),
267+
LinkedList(1),
268+
LinkedList(2, 2)
269+
),
270+
(
271+
LinkedList(5),
272+
LinkedList(2, 1),
273+
LinkedList(7, 1)
249274
)
250275
]
251276

0 commit comments

Comments
 (0)