Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialDerek Derek
8,744 Points[python] recursion stops in the middle
I would like to find ALL pairs that sum to x in a linked list, but the code I have right now only finds the first such pair. How can i modify my recursive function to find the second pair in my example (i.e., catch 5, 7 pair) as well?
class Node:
def __init__(self, val):
self.val = val
self.next = None
self.prev = None
class LinkedList:
'''doubly linked list'''
def __init__(self, head):
self.head = Node(head)
self.tail = None
self.pairs = []
self.length = 1
def add(self, item):
cur = self.head
while cur.next is not None:
cur = cur.next
cur.next = Node(item)
self.length += 1
# make linked list doubly
cur.next.prev = cur
# set tail of linked list
self.tail = cur.next
def findSummingPair(self, x, head, tail):
current_sum = head.val + tail.val
if current_sum == x:
self.pairs.append((head.val, tail.val))
else:
if current_sum < x:
# print current_sum, x
return self.findSummingPair(x, head.next, tail)
else:
# print current_sum, x
return self.findSummingPair(x, head, tail.prev)
return self.pairs
ll = LinkedList(1)
ll.add(2)
ll.add(5)
ll.add(7)
ll.add(10)
ll.add(15)
# print ll.head.next.next.prev.val
# print ll.tail.val
print ll.findSummingPair(12, ll.head, ll.tail)