def union(llist_1, llist_2):
    # edge case, if either of the lists is null, we return the other list
    if llist_1 is None or llist_1.head is None:
        return llist_2
    if llist_2 is None or llist_2.head is None:
        return llist_1

    # the final linked list which we will return
    unioned_list = LinkedList()

    # in union, we need to make sure that elements in list 1 aren't repeated in list 2
    # so we need to use a set to ensure no duplicates
    unioned_set = set()

    # we loop through the first linked list, and add its elements to the set
    current_node = llist_1.head
    while current_node is not None:
        unioned_set.add(current_node.value)
        current_node = current_node.next

    # we loop through the second linked list, and add its elements to the set
    current_node = llist_2.head
    while current_node is not None:
        unioned_set.add(current_node.value)
        current_node = current_node.next

    # now we create the final linked list and return it
    for value in unioned_set:
        unioned_list.append(value)

    return unioned_list
    def test_right_append(self):
        ll = LinkedList()
        ll.right_append(5)
        ll.right_append(7)

        self.assertEqual(ll.head.data, 5)
        self.assertEqual(ll.head.pointer_next.data, 7)
        self.assertIsNone(ll.head.pointer_next.pointer_next)
    def test_delete_last_el(self):
        n1 = Node(1)
        n2 = Node(7)
        n1.pointer_next = n2
        ll = LinkedList(n1)
        ll.delete_last_el()

        self.assertEqual(ll.head.data, 1)
        self.assertIsNone(ll.head.pointer_next)
    def test__delitem__(self):
        """ Removes an item by index"""
        n1 = Node(12)
        n2 = Node(2)
        n1.pointer_next = n2
        ll = LinkedList(n1)
        self.assertRaises(IndexError, ll.__delitem__, 2)
        self.assertRaises(TypeError, ll.__delitem__, "Ivan")

        ll.__delitem__(1)
        self.assertEqual(len(ll), 1)
        self.assertEqual(ll[0].data, 12)
 def test__getitem__(self):
     """ get by index an element : l[]"""
     ll = LinkedList(Node(10))
     self.assertRaises(IndexError, ll.__getitem__, 2)
     self.assertRaises(TypeError, ll.__getitem__, False)
     self.assertRaises(TypeError, ll.__getitem__, "test data")
     self.assertEqual(ll[0].data, 10)
     self.assertEqual(ll[-1].data, 10)
 def test__iter__(self):
     ll = LinkedList()
     ll.right_append(100)
     ll.right_append(99)
     ll.left_append(0)
     iterator = iter(ll)
     self.assertEqual(next(iterator), 0)
     self.assertEqual(next(iterator), 100)
     self.assertEqual(next(iterator), 99)
     self.assertRaises(StopIteration, next, iterator)
Exemple #7
0
    def __createdVertexInsertion(self, v):
        '''
        This is a helper function to simply inserted a given vertex into a 
        hash table of existing vertices
        INPUT:
            v: Vertex that we are inserting
        OUTPUT:
            Graph with a new given vertex
        '''

        self.vertices[v] = LinkedList.LinkedList()
def getBuzzfeed(word):
	firstNode = LinkedListNode("")
	firstNode.setNext(None)
	LLlist= LinkedList(firstNode)
	jsonStr = '{ \"results\": ['
	url = "http://www.buzzfeed.com/tag/"+word
	html = urllib.urlopen(url).read()
	htmlObject = BeautifulSoup(html, features="lxml")
	headlines = []
	count =0
	##print ("Second tag")
	##print (htmlObject)
	for item in htmlObject.findAll(re.compile("h2", re.S)):
		if count <3:
		#	#print(item)
			pattern = re.compile("<a href=\"(.*)\" rel:gt_act=\"post/titl.*>(.*)</a>", re.S)
			match = pattern.match(repr(item.a))
			if match != None:
				url = "http://www.buzzfeed.com"+match.groups()[0]
				match= match.groups()[1].replace("\\n\\t\\t\\n\\t\\t\\t","")
				match = match.replace("\\xa0", " ")
				match = match.replace('u201c', ' ')
				match = match.replace('u201d', ' ')
				match = match.replace('u2026', ' ')
				match = match.replace("\\n\\t\\t", "")
				match = re.sub(r'\W+', ' ', match)
				match = match.replace("u2019", "'")
				node = LinkedListNode(url)
				node.setTitle(match)
				LLlist.insertFirst(node)
				count= count+1
	currentJSON = LLlist.deleteFirst()
	while(currentJSON.getNext().getNext() != None):
		jsonStr+= " {\"title\": \" "+currentJSON.getTitle()+ "\", \"url\": \""+currentJSON.getURL() +"\" }, "
		currentJSON = LLlist.deleteFirst()

	jsonStr+= " {\"title\": \" "+currentJSON.getTitle()+ "\", \"url\": \""+currentJSON.getURL() +"\" } "
	jsonStr+= ' ]}'
	sentiment = getSentiment(getBuzzfeedPost(jsonStr), word) 
	return sentiment
    def test_left_append(self):
        ll = LinkedList()
        ll.left_append(3)
        ll.left_append(1000)

        self.assertEqual(ll.head.data, 1000)
        self.assertEqual(ll.head.pointer_next.data, 3)
        self.assertIsNone(ll.head.pointer_next.pointer_next)
    def bstToLinkedLst(self):
        '''
        This converts a binary search tree into a linked list. In order to achieve this we need
        to do a inorder traversal and then simply insert the list into our linked list.
        INPUT: None
        OUTPUT:
            Binary tree to a doubly linked list
        
        '''

        linked = LinkedList.LinkedList()
        lst = self.inOrderTraverasl()
        linked.insertList([node.getData() for node in lst])
        return linked
Exemple #11
0
def intersection(llist_1, llist_2):
    # edge case, if any of the lists is null, we return null
    if llist_1 is None or llist_2 is None:
        return None
    if llist_1.head is None or llist_2.head is None:
        return None
    
    # the final linked list which we will return
    intersected_list = LinkedList()

    # in intersection, we need to store items which appear in both lists
    # so we use a set to store the elements in list 1
    set_1 = set()
    # and another set to store the intersected elements
    intersected_set = set()

    # we loop through the first linked list, and add its elements to set 1
    current_node = llist_1.head
    while current_node is not None:
        set_1.add(current_node.value)
        current_node = current_node.next

    # we loop through the second linked list
    current_node = llist_2.head
    while current_node is not None:
        # if the value of the current node exists in list 1, we add it to our final set
        if current_node.value in set_1:
            intersected_set.add(current_node.value)
        current_node = current_node.next
    
    # now we add the intersected elements to our final linked list and return it
    for value in intersected_set:
        intersected_list.append(value)
    
    # if the intersection is an empty list, we return None
    # otherwise we return the list
    return intersected_list if intersected_list.head is not None else None
Exemple #12
0
    def __init__(self):
        '''
        Our graph will keep track of a set of vertices and a linked list of edges as
        mentioned in the description of an adjacency list.

        Runtime
        Implementation 1: O(n)
        Implementation 2: O(n ^ 2)
        Implementation 3: O(n)
        '''

        self.vertices = {}
        self.edges = LinkedList.LinkedList()
        self.connectedComponents = 0
        self.cycles = False
Exemple #13
0
    def __init__(self, head = None):
        '''
        A constructor for our queue.
        INPUT:
            head: Head of a chain of nodes (if applicable).
        OUTPUT:
            Queue
            
        We defined one class variables:
        queue = A linked list, that is composed of variables such as size, 
        nodes, and functionality that can be seen in the linked list folder. 
        The queue can automatically be initialized from an existing 
        chain of nodes. Check out initializer() in the linked list class.
        '''

        self.queue = LinkedList.LinkedList(head)
Exemple #14
0
    def insertVertex(self, key):
        '''
        Here all we do is create a new vertex object with the key parameter and insert it
        into our set of vertices. The reason we use a set is because it is implemented
        using a hashtable and allows us to have constant lookups.
        INPUT:
            key: Key or data we want to insert
        OUTPUT:
            Inserted vertex into our graph

        Runtime
        Implementation 1: O(1)
        Implementation 2: O(1) + O(n) amortized
        Implementation 3: O(1) ?
        '''

        vert = Vertex(key)
        self.vertices[vert] = LinkedList.LinkedList()
    def test_right_append_empty_list(self):
        ll = LinkedList()
        ll.right_append(700)

        self.assertEqual(ll.head.data, 700)
        self.assertIsNone(ll.head.pointer_next)
Exemple #16
0
    count = 0
    node = input_list.get_root()
    while node is not None:
        count += 1
        node = node.get_next()
    return count


def recursive_count(input_list):
    node = input_list.get_root()
    return _recursive_count(node, 0)


def _recursive_count(node, count):
    if node is not None:
        return _recursive_count(node.get_next(), count + 1)
    return count


cool_list = LinkedList()
cool_list.insert(1)
cool_list.insert(1)
cool_list.insert(2)
cool_list.insert(1)
cool_list.insert(1)

cool_list.in_order()

print()
print(iterate_count(cool_list))
print(recursive_count(cool_list))
 def test_left_append_empty_list(self):
     ll = LinkedList()
     ll.left_append(10)
     self.assertCountEqual(ll, LinkedList(Node(10)))
 def test__contains__(self):
     ll = LinkedList()
     ll.right_append(3)
     ll.right_append(5)
     self.assertEqual(ll.__contains__(3), True)
     self.assertEqual(ll.__contains__(10), False)
Exemple #19
0
from Node import Node
from Linked_List import LinkedList

if __name__ == '__main__':
    """
    help()
    The Python help function can be super helpful for easily pulling up documentation for classes and methods. 
    We can call the help function on one of our classes, which will return some basic info about the methods defined 
    in our class

    """
    """create LinkedList"""
    n1 = Node(1)
    n2 = Node(7)
    n1.pointer_next = n2
    ll = LinkedList(n1)
    ll.left_append(100)
    print(ll)
    # # ll = LinkedList()
    # print(ll)
    # if ll:
    #     print("Not empty!")
    """length of LinkedList"""

    # print(len(ll))
    """append to left"""
    # print(ll)
    # ll.left_append(42)
    # ll.left_append(2)
    # print(ll)
    """check list for emptiness"""
 def test__delitem__empty_list(self):
     self.assertRaises(IndexError, LinkedList().__delitem__, 0)
 def test__len__list(self):
     n1 = Node(1)
     n2 = Node(7)
     n1.pointer_next = n2
     ll = LinkedList(n1)
     self.assertEqual(len(ll), 2)
 def test__len__empty_list(self):
     ll = LinkedList()
     self.assertEqual(len(ll), 0)
Exemple #23
0
#             itr = itr.prev
#         return print('Doubly Linked List in reverse: ', revs)

if __name__ == '__main__':
    # dll = DoublyLinkedList()
    # dll.print()
    # dll.insert_at_beginning(30)
    # dll.print()
    # dll.insert_at_beginning(10)
    # dll.print()
    # dll.insert_at_end(40)
    # dll.print()
    # dll.insert_at(20, 1)
    # dll.print()
    # dll.insert_at_end(50)
    # dll.print()
    # dll.insert_at(25,2)
    # dll.print()
    # dll.remove_at(2)
    # dll.print()
    # dll.insert_after_value(40, 45)
    # dll.print()
    # dll.remove_by_value(45)
    # dll.print()
    # dll.print_forward()
    # dll.print_reverse()
    ll = LinkedList()
    ll.insert_values([1, 2, 3, 4, 5, 6])
    ll.print()
    ll.insert_at(2, 200)
    ll.print()
    '머리노드삽입', '꼬리노드삽입', '머리노드삭제', '꼬리노드삭제', '주목노드출력', '주목노드이동', '주목노드삭제',
    '모든노드삭제', '검색', '멤버십판단', '모든노드출력', '스캔', '종료'
])


def select_menu() -> Menu:

    s = [f'({m.value}){m.name}' for m in Menu]
    while True:
        print(*s, sep=' ', end='')
        n = int(input(' : '))
        if 1 <= n <= len(Menu):
            return Menu(n)


lst = LinkedList()

while True:
    menu = select_menu()

    if menu == Menu.머리노드삽입:
        lst.add_first(int(input('머리노드를 넣을 값을 입력하세요 : ')))

    elif menu == Menu.꼬리노드삽입:
        lst.add_last(int(input('꼬리노드를 넣을 값을 입력하세요 : ')))

    elif menu == Menu.머리노드삭제:
        lst.remove_first()

    elif menu == Menu.꼬리노드삭제:
        lst.remove_last()
from Linked_List import LinkedList
from Union import union
from Intersection import intersection

# Test case 1, 2 linked lists with elements in union and intersection
print("\nChecking TEST_CASE_1: 2 linked lists with elements in union and intersection\n")

linked_list_1 = LinkedList()
linked_list_2 = LinkedList()

element_1 = [3,2,4,35,6,65,6,4,3,21]
element_2 = [6,32,4,9,6,1,11,21,1]

for i in element_1:
    linked_list_1.append(i)

for i in element_2:
    linked_list_2.append(i)


print (union(linked_list_1,linked_list_2))
print (intersection(linked_list_1,linked_list_2))
'''
Checking TEST_CASE_1: 2 linked lists with elements in union and intersection

32 -> 65 -> 2 -> 35 -> 4 -> 6 -> 1 -> 9 -> 11 -> 3 -> 21 -> 
4 -> 21 -> 6 -> 
'''

# Test case 2, 2 linked lists with elements in union but no intersection
print("\nChecking TEST_CASE_2: 2 linked lists with elements in union but no intersection\n")
 def test_delete_last_el_empty_list(self):
     ll = LinkedList()
     self.assertRaises(ValueError, ll.delete_last_el)
 def test__str__list(self):
     n1 = Node(1)
     n2 = Node(7)
     n1.pointer_next = n2
     ll = LinkedList(n1)
     self.assertEqual(str(ll), "LinkedList(1, 7)")
Exemple #28
0
    def __init__(self, num_elements):

        self.num_elements = num_elements
        self.main_array = [LinkedList() for i in range(0, num_elements)]
 def test__str__empty_list(self):
     ll = LinkedList()
     self.assertEqual(str(ll), "LinkedList()")
Exemple #30
0
from Linked_List import LinkedList

LL1 = LinkedList(93)
LL2 = LinkedList(94, LL1)

print LL2.getChild().getData()
 def test__bool__(self):
     """Unittest checks if __bool__ method works correctly"""
     n1 = Node(1)
     ll = LinkedList(n1)
     self.assertTrue(ll)
     self.assertFalse(LinkedList())