コード例 #1
1
def basic_tests():
	sll = SLL()

	try:
		sll.pop_back()
	except UnderFlowError as e:
		print "Tried popping from an empty SLL. Error:", e

	sll.push_back(1)
	assert(sll.size == 1)
	assert(sll.head.value == 1) 
	assert(sll.tail.value == 1) 

	sll.push_front(0)
	assert(sll.size == 2)
	assert(sll.head.value == 0) 
	assert(sll.tail.value == 1) 


	sll.push_back(2)
	assert(sll.size == 3)
	assert(sll.head.value == 0) 
	assert(sll.tail.value == 2) 

	sll.push_back(3)
	assert(sll.size == 4)
	assert(sll.head.value == 0) 
	assert(sll.tail.value == 3) 

	sll.push_back(4)
	assert(sll.size == 5)
	assert(sll.head.value == 0) 
	assert(sll.tail.value == 4) 

	assert(4 == sll.pop_back())
	assert(sll.size == 4)
	assert(sll.head.value == 0) 
	assert(sll.tail.value == 3) 

	assert(0 == sll.pop_front())
	assert(sll.size == 3)
	assert(sll.head.value == 1) 
	assert(sll.tail.value == 3) 

	assert(1 == sll.pop_front())
	assert(sll.size == 2)
	assert(sll.head.value == 2) 
	assert(sll.tail.value == 3) 

	assert(3 == sll.pop_back())
	assert(sll.size == 1)
	assert(sll.head.value == 2) 
	assert(sll.tail.value == 2) 


	assert(2 == sll.pop_back())
	assert(sll.size == 0)
	assert(sll.head == None) 
	assert(sll.tail == None) 


	# fromList and toList
	assert(SLL.toList(SLL.fromList(range(9, 0, -2))) == range(9, 0, -2))
コード例 #2
0
def test_iterator():
	s = SLL()
	for i in range(10):
		s.push_back(i+1)

	# Using for/in -> implicit next()
	it = iter(s)
	i = 1
	for x in it:
		assert(x == i)
		i = i + 1


	# Using the next/iter methods
	it = iter(s)
	i = 1
	while it:
		try:
			assert(it.next() == i)
		except StopIteration:
			break
		i = i + 1


	# Use an external next() on the iterator as opposed to it.next()
	it = iter(s)
	i = 1
	while it:
		try:
			assert(next(it) == i)
		except StopIteration:
			break
		i = i + 1
コード例 #3
0
def test_iterator():
    s = SLL()
    for i in range(10):
        s.push_back(i + 1)

    # Using for/in -> implicit next()
    it = iter(s)
    i = 1
    for x in it:
        assert (x == i)
        i = i + 1

    # Using the next/iter methods
    it = iter(s)
    i = 1
    while it:
        try:
            assert (it.next() == i)
        except StopIteration:
            break
        i = i + 1

    # Use an external next() on the iterator as opposed to it.next()
    it = iter(s)
    i = 1
    while it:
        try:
            assert (next(it) == i)
        except StopIteration:
            break
        i = i + 1
コード例 #4
0
def test_len():
	sll = SLL()

	assert(not sll == True)
	if not sll:
		assert(len(sll) == 0)

	sll.push_back(1)

	if sll:
		assert(len(sll) == 1)
コード例 #5
0
def test_len():
    sll = SLL()

    assert (not sll == True)
    if not sll:
        assert (len(sll) == 0)

    sll.push_back(1)

    if sll:
        assert (len(sll) == 1)
コード例 #6
0
    def top_view_LR(self, aggregate_fn=_default_printfn, **kwargs):
        if not self.root:
            return

        # Queue to help with level-order traversal
        q = Queue()

        # Store L/R width of a node and its value if it is visible in the top-view, in a sorted list
        # ordered by the width
        # at the end of the level-order traversal the list would contain
        # [(-max_left_width, node value), ...., (0, root.value), ... (max_right_width, node value)]
        slist = SLL()

        # pairs a(w1, node_val1) vs b(w2, node_val2) are valued against each other
        # depending on w1 vs w2 (where w1 and w2 are widths, so slist is kept sorted by the nodes' L/R widths)
        pair_comparator = lambda (w1, node_val1), (w2, node_val2): cmp(w1, w2)

        min_width = 0
        max_width = 0
        q.enqueue((0, self.root))

        # Top-view begins with the root node
        slist.place((0, self.root.value))
        while q.length() != 0:
            width, node = q.dequeue()

            if width < min_width:
                min_width = width
                slist.place((width, node.value))
            elif width > max_width:
                max_width = width
                slist.place((width, node.value))

            # NOTE: width 0, is root, would already be filled in at root,
            # and in a top-view is not going to replaced

            q.enqueue((width - 1, node.left)) if node.left else None
            q.enqueue((width + 1, node.right)) if node.right else None

        # At the end of the level-order traversal,
        # slist is ordered by width, so
        # (-max_left_width, ..., 0, ..., max_right_width)
        # Just retrieve the SLL L-R for the top view (L-R)
        while slist.size != 0:
            width, item = slist.pop_front()
            aggregate_fn(kwargs, item)
コード例 #7
0
def test_indexing():
	sll = SLL.fromList(range(1,11))

	for i in range(10):
		assert(sll[i] == i+1)
		
	try:
		assert(sll[10] == None)
	except IndexError:
		print "sll[10] index error on sll, SLL has only %d elements" %(len(sll))

	for i in range(1,11):
		assert(sll[-i] == 10-i+1)

	try:
		assert(sll[-11] == None)
	except IndexError:
		print "sll[-11] index error on sll, SLL has only %d elements" %(len(sll))
コード例 #8
0
def test_indexing():
    sll = SLL.fromList(range(1, 11))

    for i in range(10):
        assert (sll[i] == i + 1)

    try:
        assert (sll[10] == None)
    except IndexError:
        print "sll[10] index error on sll, SLL has only %d elements" % (
            len(sll))

    for i in range(1, 11):
        assert (sll[-i] == 10 - i + 1)

    try:
        assert (sll[-11] == None)
    except IndexError:
        print "sll[-11] index error on sll, SLL has only %d elements" % (
            len(sll))
コード例 #9
0
def test_find():
    s = SLL()
    for x in [6, 4, 2]:
        s.place(x)

    for x in [5, 1]:
        s.place(x)

    s.place(0)
    s.place(7)

    assert s.find(0) == 0
    assert s.find(7) == 7
    assert s.find(1) == 1
    assert s.find(2) == 2
    assert s.find(4) == 4
    assert s.find(3) == None
    assert s.find(10) == None
    assert s.find(-1) == None

    # Test custom comparator
    s2 = SLL.fromList([(2, 1), (1, 'a'), (2, 3), (0, 'c'), (4, 1), (3, 0)])
    assert s2.find((2, 1)) == (2, 1)
    assert s2.find((4, 3), comparatorfn=lambda (a, b),
                   (c, d): cmp(b, d)) == (2, 3)

    # compare only the first item in the pair between two nodes
    assert s2.find((2, 100), comparatorfn=lambda (a, b),
                   (c, d): cmp(a, c)) == (2, 1)
    assert s2.find((0, 100), comparatorfn=lambda (a, b),
                   (c, d): cmp(a, c)) == (0, 'c')
コード例 #10
0
def test_find():
	s = SLL()
	for x in [6,4,2]:
		s.place(x)

	for x in [5, 1]:
		s.place(x)

	s.place(0)
	s.place(7)

	assert s.find(0) == 0
	assert s.find(7) == 7
	assert s.find(1) == 1
	assert s.find(2) == 2
	assert s.find(4) == 4
	assert s.find(3) == None
	assert s.find(10) == None
	assert s.find(-1) == None

	# Test custom comparator
	s2  = SLL.fromList([(2,1), (1, 'a'), (2, 3), (0, 'c'), (4,1), (3,0)])
	assert s2.find((2,1)) == (2,1)
	assert s2.find((4,3), comparatorfn = lambda (a,b),(c,d): cmp(b,d)) == (2,3)

	# compare only the first item in the pair between two nodes
	assert s2.find((2,100), comparatorfn = lambda (a,b),(c,d): cmp(a,c)) == (2,1)
	assert s2.find((0,100), comparatorfn = lambda (a,b),(c,d): cmp(a,c)) == (0, 'c')
コード例 #11
0
def test_findMatchingNode():
	s = SLL()
	for x in [6,4,2]:
		s.place(x)

	for x in [5, 1]:
		s.place(x)

	s.place(0)
	s.place(7)

	assert s.findMatchingNode(0) == s.head
	assert s.findMatchingNode(7) == s.tail
	assert s.findMatchingNode(1) == s.head.next
	assert s.findMatchingNode(2) == s.head.next.next
	assert s.findMatchingNode(4) == s.head.next.next.next
	assert s.findMatchingNode(3) == None
	assert s.findMatchingNode(10) == None
	assert s.findMatchingNode(-1) == None

	# Test custom comparator
	s2  = SLL.fromList([(2,1), (1, 'a'), (2, 3), (0, 'c'), (4,1), (3,0)])
	assert s2.findMatchingNode((2,1)) == s2.head
	assert s2.findMatchingNode((2,3), comparatorfn = lambda (a,b),(c,d): cmp(b,d)) == s2.head.next.next

	# compare only the first item in the pair between two nodes
	assert s2.findMatchingNode((2,100), comparatorfn = lambda (a,b),(c,d): cmp(a,c)) == s2.head
	node = s2.findMatchingNode((0,100), comparatorfn = lambda (a,b),(c,d): cmp(a,c))

	# change node's value
	node.value = (0, 'e')
	assert node == s2.head.next.next.next
	assert node.value == (0, 'e')
	assert SLL.toList(s2) == [(2,1), (1, 'a'), (2, 3), (0, 'e'), (4,1), (3,0)]
コード例 #12
0
		# then again, next k-blocks begin at start.next (d->g), start = 'g'
		# then later, start becomes 'i', and next k-block begins at start.next = 'j'
		start = start.next
		tmp = reverse_k_group(start, k)

		# If we had k-nodes to begin with, link last block to this reversed block
		# if reverse_k_group() returned None, we are left with fewer than k nodes
		# at the end, return immediately
		if tmp:
			last.next = tmp




if __name__ == '__main__':
	sll = SLL.fromList("abcde")
	assert(lookahead(sll.head, 4) == True)
	assert(lookahead(sll.head, 5) == True)
	assert(lookahead(sll.head, 6) == False)
	tmp = reverse_k_group(sll.head, 4)
	sll.head = tmp
	assert(SLL.toList(sll) ==  map (lambda x: x, "dcbae"))

	sll2 = SLL.fromList("abcde")
	tmp = reverse_k_group(sll2.head, 6)
	assert(tmp == None)
	assert(SLL.toList(sll2) ==  map (lambda x: x, "abcde"))

	sll = SLL.fromList("abcde")
	reverse(sll, 2)
	assert(SLL.toList(sll) ==  map (lambda x: x, "badce"))
コード例 #13
0
def test_reverse():
	sll = SLL()
	sll.push_back(1)
	sll.push_back(2)
	sll.push_back(3)
	sll.push_back(4)

	sll.reverse()

	it = iter(sll)
	i = 4
	for x in it:
		assert(x == i)
		i -= 1


	# sll itself returns an SLLIterator, so we needn't get an iterator to
	# traverse the sll
	i = 4
	for x in sll:
		assert(x == i)
		i -= 1

	s2 = SLL()
	s2.push_back('a')
	s2.reverse()
	assert(s2.size == 1)
	assert(s2.head.value == 'a')
	assert(s2.tail.value == 'a')

	s2.push_back('b')
	s2.reverse()
	assert(s2.size == 2)
	assert(s2.head.value == 'b')
	assert(s2.tail.value == 'a')
コード例 #14
0
	def __init__(self, vertices, directed=False):
		GraphBase.__init__(self, vertices, directed)
		self._adjlists = [SLL() for x in xrange(vertices)]
コード例 #15
0
def test_place():
    s = SLL()
    for x in [6, 4, 2]:
        s.place(x)

    for x in [5, 3, 1]:
        s.place(x)

    s.place(0)
    s.place(7)

    # wont get added
    s.place(0, allowduplicates=False)
    s.place(4, allowduplicates=False)
    s.place(7, allowduplicates=False)

    l = []
    collate_fn = lambda kwargs, data: kwargs['lst'].append(data)
    s.traverse(collate_fn, lst=l)
    assert (l == range(8))

    # Test custom comparator
    s2 = SLL()
    test_list = [(2, 1), (1, 'a'), (2, 3), (0, 'c'), (4, 1), (3, 0)]
    for x in test_list:
        s2.place(x, lambda (a, b), (c, d): cmp(a, c))

    # Duplicates, won't get added
    s2.place((0, 'c'), allowduplicates=False)
    s2.place((2, 1), allowduplicates=False)
    s2.place((4, 1), allowduplicates=False)

    l = []
    collate_fn = lambda xargs, data: xargs['lst'].append(data)
    s2.traverse(collate_fn, lst=l)
    assert (l == [(0, 'c'), (1, 'a'), (2, 1), (2, 3), (3, 0), (4, 1)])

    # Test custom comparator2
    s3 = SLL()
    test_list = [(2, 1), (1, 'a'), (2, 3), (0, 'c'), (4, 1), (3, 0)]
    for x in test_list:
        s3.place(x, lambda (a, b), (c, d): cmp(b, d))

    l = []
    collate_fn = lambda xargs, data: xargs['lst'].append(data)
    s3.traverse(collate_fn, lst=l)
    assert l == [(3, 0), (2, 1), (4, 1), (2, 3), (1, 'a'), (0, 'c')]
コード例 #16
0
def test_place():
	s = SLL()
	for x in [6,4,2]:
		s.place(x)

	for x in [5, 3, 1]:
		s.place(x)

	s.place(0)
	s.place(7)

	# wont get added
	s.place(0, allowduplicates=False)
	s.place(4, allowduplicates=False)
	s.place(7, allowduplicates=False)

	l = []
	collate_fn = lambda kwargs, data : kwargs['lst'].append(data)
	s.traverse(collate_fn, lst=l)
	assert(l == range(8))

	# Test custom comparator
	s2 = SLL()
	test_list = [(2,1), (1, 'a'), (2, 3), (0, 'c'), (4,1), (3,0)]
	for x in test_list:
		s2.place(x, lambda (a,b),(c,d): cmp(a, c))

	# Duplicates, won't get added
	s2.place((0, 'c'), allowduplicates=False)
	s2.place((2, 1), allowduplicates=False)
	s2.place((4, 1), allowduplicates=False)

	l = []
	collate_fn = lambda xargs, data : xargs['lst'].append(data)
	s2.traverse(collate_fn, lst=l)
	assert(l == [(0, 'c'), (1, 'a'), (2, 1), (2, 3), (3, 0), (4, 1)])

	# Test custom comparator2
	s3 = SLL()
	test_list = [(2,1), (1, 'a'), (2, 3), (0, 'c'), (4,1), (3,0)]
	for x in test_list:
		s3.place(x, lambda (a,b),(c,d): cmp(b, d))

	l = []
	collate_fn = lambda xargs, data : xargs['lst'].append(data)
	s3.traverse(collate_fn, lst=l)
	assert l == [(3, 0), (2, 1), (4, 1), (2, 3), (1, 'a'), (0, 'c')]
コード例 #17
0
def test_findMatchingNode():
    s = SLL()
    for x in [6, 4, 2]:
        s.place(x)

    for x in [5, 1]:
        s.place(x)

    s.place(0)
    s.place(7)

    assert s.findMatchingNode(0) == s.head
    assert s.findMatchingNode(7) == s.tail
    assert s.findMatchingNode(1) == s.head.next
    assert s.findMatchingNode(2) == s.head.next.next
    assert s.findMatchingNode(4) == s.head.next.next.next
    assert s.findMatchingNode(3) == None
    assert s.findMatchingNode(10) == None
    assert s.findMatchingNode(-1) == None

    # Test custom comparator
    s2 = SLL.fromList([(2, 1), (1, 'a'), (2, 3), (0, 'c'), (4, 1), (3, 0)])
    assert s2.findMatchingNode((2, 1)) == s2.head
    assert s2.findMatchingNode((2, 3),
                               comparatorfn=lambda (a, b),
                               (c, d): cmp(b, d)) == s2.head.next.next

    # compare only the first item in the pair between two nodes
    assert s2.findMatchingNode((2, 100),
                               comparatorfn=lambda (a, b),
                               (c, d): cmp(a, c)) == s2.head
    node = s2.findMatchingNode((0, 100),
                               comparatorfn=lambda (a, b), (c, d): cmp(a, c))

    # change node's value
    node.value = (0, 'e')
    assert node == s2.head.next.next.next
    assert node.value == (0, 'e')
    assert s2.toList() == [(2, 1), (1, 'a'), (2, 3), (0, 'e'), (4, 1), (3, 0)]
コード例 #18
0
def basic_tests():
    sll = SLL()

    try:
        sll.pop_back()
    except UnderFlowError as e:
        print "Tried popping from an empty SLL. Error:", e

    sll.push_back(1)
    assert (sll.size == 1)
    assert (sll.head.value == 1)
    assert (sll.tail.value == 1)

    sll.push_front(0)
    assert (sll.size == 2)
    assert (sll.head.value == 0)
    assert (sll.tail.value == 1)

    sll.push_back(2)
    assert (sll.size == 3)
    assert (sll.head.value == 0)
    assert (sll.tail.value == 2)

    sll.push_back(3)
    assert (sll.size == 4)
    assert (sll.head.value == 0)
    assert (sll.tail.value == 3)

    sll.push_back(4)
    assert (sll.size == 5)
    assert (sll.head.value == 0)
    assert (sll.tail.value == 4)

    assert (4 == sll.pop_back())
    assert (sll.size == 4)
    assert (sll.head.value == 0)
    assert (sll.tail.value == 3)

    assert (0 == sll.pop_front())
    assert (sll.size == 3)
    assert (sll.head.value == 1)
    assert (sll.tail.value == 3)

    assert (1 == sll.pop_front())
    assert (sll.size == 2)
    assert (sll.head.value == 2)
    assert (sll.tail.value == 3)

    assert (3 == sll.pop_back())
    assert (sll.size == 1)
    assert (sll.head.value == 2)
    assert (sll.tail.value == 2)

    assert (2 == sll.pop_back())
    assert (sll.size == 0)
    assert (sll.head == None)
    assert (sll.tail == None)

    # fromList and toList
    assert (SLL.fromList(range(9, 0, -2)).toList() == range(9, 0, -2))
コード例 #19
0
def test_reverse():
    sll = SLL()
    sll.push_back(1)
    sll.push_back(2)
    sll.push_back(3)
    sll.push_back(4)

    sll.reverse()

    it = iter(sll)
    i = 4
    for x in it:
        assert (x == i)
        i -= 1

    # sll itself returns an SLLIterator, so we needn't get an iterator to
    # traverse the sll
    i = 4
    for x in sll:
        assert (x == i)
        i -= 1

    s2 = SLL()
    s2.push_back('a')
    s2.reverse()
    assert (s2.size == 1)
    assert (s2.head.value == 'a')
    assert (s2.tail.value == 'a')

    s2.push_back('b')
    s2.reverse()
    assert (s2.size == 2)
    assert (s2.head.value == 'b')
    assert (s2.tail.value == 'a')
コード例 #20
0
        # Have 'trail' follow 'trav' until
        # trav 'falls off' end of the SLL
        # placing 'trav' at nth node from the end
        trail = sll.head
        while trav:
            trail = trail.next
            trav = trav.next

        return trail.value
    except:  # SLL has <n items
        raise UnderFlowError


if __name__ == "__main__":
    sll1 = SLL.fromList([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
    assert (find_last_nth(sll1, 0) == 1)
    assert (find_last_nth_size_known(sll1, 0) == 1)

    assert (find_last_nth(sll1, 3) == 8)
    assert (find_last_nth_size_known(sll1, 3) == 8)
    assert (find_last_nth(sll1, 1) == 10)
    assert (find_last_nth_size_known(sll1, 1) == 10)
    assert (find_last_nth(sll1, 10) == 1)
    assert (find_last_nth_size_known(sll1, 10) == 1)
    try:
        assert (find_last_nth(sll1, 11) == None)
    except UnderFlowError:
        print "1: Underflow error as expected!"

    try:
コード例 #21
0
ファイル: sort.py プロジェクト: Ibnmardanis24/Development
			curr = prev.next
			# All nodes until 'prev' is sorted
			# 'curr' < 'prev' => yank it and place it to the left
			if curr.value < prev.value:
				yank(prev, curr)
				place(curr)
			else:
				# 'curr' is already in the right place
				# advance 'prev' to next node, i,e 'curr'
				prev = curr


			
if __name__ == '__main__':
	l = [2,5,1,4,3]
	s = SLL.fromList(l)
	Sort.insertion_sort(s)
	assert sorted(l) == s.toList()

	l = [2,4,6,1,3,5]
	s = SLL.fromList(l)
	Sort.insertion_sort(s)
	assert sorted(l) == s.toList()

	l = [1,3,5,2,4,6]
	s = SLL.fromList(l)
	Sort.insertion_sort(s)
	assert sorted(l) == s.toList()

	l = [1,2,3,4,5,6]
	s = SLL.fromList(l)
コード例 #22
0
		# Have 'trail' follow 'trav' until
		# trav 'falls off' end of the SLL
		# placing 'trav' at nth node from the end
		trail = sll.head
		while trav:
			trail = trail.next
			trav = trav.next

		return trail.value
	except: # SLL has <n items
		raise UnderFlowError


if __name__ == "__main__":
	sll1 = SLL.fromList([1,2,3,4,5,6,7,8,9,10])
	assert(find_last_nth(sll1, 0) == 1)
	assert(find_last_nth_size_known(sll1, 0) == 1)

	assert(find_last_nth(sll1, 3) == 8)
	assert(find_last_nth_size_known(sll1, 3) == 8)
	assert(find_last_nth(sll1, 1) == 10)
	assert(find_last_nth_size_known(sll1, 1) == 10)
	assert(find_last_nth(sll1, 10) == 1)
	assert(find_last_nth_size_known(sll1, 10) == 1)
	try:
		assert(find_last_nth(sll1, 11) == None)
	except UnderFlowError:
		print "1: Underflow error as expected!"

	try: