def create_linked_list(alist): """Given a Python list, create linked list in same order.""" if len(alist) == 0: return None first = Node(alist[0]) first.next = create_linked_list(alist[1:]) return first
def test_damaged_recursive_data_structures(self): from ch06.expression import Expression, Value, add from algs.node import Node n = Node(3) n.next = n # This is dangerous! with self.assertRaises(RuntimeError): print(sum_list(n)) a = Expression(add, Value(1), Value(5)) a.left = a # This is dangerous! with self.assertRaises(RuntimeError): print(a.eval())
def tournament_two_losers(A): """ Returns two largest values in A. Only works for lists whose length is a power of 2. Each winner accumulates list of the values it beat, from which you call max() to find the second largest. """ from algs.node import Node if len(A) < 2: raise ValueError('Must have at least two values') if len(A) % 2 == 1: raise ValueError('Only works for lists with even number of values.') tourn = None for i in range(0, len(A), 2): tourn = Node(ExtendedMatch(A[i], A[i+1]), tourn) while not tourn.next is None: results = None while tourn: next_one = tourn.next.next tv = tourn.value tnv = tourn.next.value if tv.larger > tnv.larger: tv.add_loser(tnv.larger) tourn.next = results # Keep tourn results = tourn else: tnv.add_loser(tv.larger) tourn.next.next = results # Keey tourn.next results = tourn.next tourn = next_one tourn = results # Find where second is hiding! m = tourn.value largest = m.larger second = max(m.smaller) return (largest,second)