Skip to content

Instantly share code, notes, and snippets.

@m00nlight
Created August 28, 2015 05:25
Show Gist options
  • Save m00nlight/c39d9c157b21441edf18 to your computer and use it in GitHub Desktop.
Save m00nlight/c39d9c157b21441edf18 to your computer and use it in GitHub Desktop.
Python list function
class Solution(object):
def addTwoNumbers(self, l1, l2):
ll1 = self.list2naive(l1)
ll2 = self.list2naive(l2)
a = 0 if ll1 == [] else int(''.join(map(str, ll1))[::-1])
b = 0 if ll2 == [] else int(''.join(map(str, ll2))[::-1])
res = a + b
return self.naive2list(map(int, list(str(res)[::-1])))
def list2naive(self, l):
ret = []
while l:
ret.append(l.val)
l = l.next
return ret
def naive2list(self, xs):
if not xs:
None
else:
h = xs.pop(0)
tail = self.naive2list(xs)
hh = ListNode(h)
hh.next = tail
return hh
def test(self):
xs = self.naive2list([1,2,3])
ys = self.naive2list([2,3,4,5])
zs = self.naive2list([])
p1 = self.naive2list([5])
rs = self.list2naive(self.addTwoNumbers(xs, ys))
rs2 = self.list2naive(self.addTwoNumbers(xs, zs))
print rs
assert(rs == [3,5,7,5])
assert(rs2 == [1,2,3])
assert(self.list2naive(self.addTwoNumbers(p1, p1)) == [0, 1])
return 'test pass'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment