def merge_sort(dllist: DoubleLinkedList) -> DoubleLinkedList:

    # if dllist.count() == 1:
    if dllist.begin.next == None:
        print(">>> base case: dllist=", dllist.dump("base case"))
        return dllist

    left = DoubleLinkedList()  # using new dllist to copy each smaller list
    right = DoubleLinkedList()

    middle = dllist.count() // 2
    print(">>> middle=", middle)
    lsize = middle
    print(">>> lsize=", lsize)
    rsize = dllist.count() - middle
    print(">>> rsize=", rsize)

    copy_sublist(dllist, left, lsize)
    copy_sublist(dllist, right, rsize)

    left = merge_sort(left)
    print(">>> ", left.dump("left="))
    right = merge_sort(right)
    print(">>> will this even run? right=", right.dump("right="))
    return merge(left, right)
def merge_sort(dllist: DoubleLinkedList) -> DoubleLinkedList:

    if dllist.count() == 1:
        return dllist

    left = DoubleLinkedList()  # using new dllist to copy each smaller list
    right = DoubleLinkedList()

    middle = dllist.count() // 2
    lsize = middle
    rsize = dllist.count() - middle

    copy_sublist(dllist, left, lsize)
    copy_sublist(dllist, right, rsize)

    left = merge_sort(left)
    right = merge_sort(right)

    return merge(left, right)
예제 #3
0
class Dictionary(object):
    def __init__(self, num_buckets=256):
        self.map = DoubleLinkedList()
        for x in range(0, num_buckets):
            self.map.push(DoubleLinkedList())

    def hash_key(self, key):
        return hash(key) % self.map.count()

    def get_bucket(self, key):
        bucket_id = self.hash_key(key)
        return self.map.get(bucket_id)

    def get_slot(self, key):
        bucket = self.get_bucket(key)

        if bucket:
            slot = bucket.begin
            while slot:
                if key == slot.value[0]:
                    return bucket, slot
                else:
                    slot = slot.next
        return bucket, None

    def get(self, key, default=None):
        bucket, slot = self.get_slot(key)
        return slot and slot.value[1] or default

    def set(self, key, value):
        bucket, slot = self.get_slot(key)
        if slot:
            slot.value = (key, value)
        else:
            bucket.push((key, value))

    def delete(self, key):
        bucket = self.get_bucket(key)
        slot = bucket.begin

        while slot:
            k, v = slot.value
            if key == k:
                bucket.detach_node(slot)
                break

    def print_list(self):
        bucket_node = self.map.begin
        while bucket_node:
            slot_node = bucket_node.value.begin
            while slot_node:
                print(slot_node.value)
                slot_node = slot_node.next
            bucket_node = bucket_node.next
def main():
    number = randint(5, 10)

    start_list = DoubleLinkedList()
    left = DoubleLinkedList()
    right = DoubleLinkedList()

    for i in range(number):
        start_list.push(randint(0, 10))

    start_list.dump("start list initialized.")

    lsize = start_list.count()
    print("\nlsize is: ", lsize)
    mid = lsize // 2
    print("\nmid is: ", mid)

    left_size = mid
    right_size = lsize - mid
    print(f"\nThe length of left is {left_size} & right is {right_size}.")

    # copy half of the list into left
    # i = 0
    # while i < mid:
    #     nodeval = start_list.unshift()
    #     left.push(nodeval)
    #     i += 1

    # replace above while block with a function call:
    copy_sublist(start_list, left, mid)

    start_list.dump("start after left copy")
    left.dump("left after copying from start")

    j = 0
    while j < right_size:
        # print(">>> start of while:  j is", j, " and right_size is", right_size)
        nodeval = start_list.unshift()
        # print(">>> nodeval is ", nodeval)
        right.push(nodeval)
        # right.dump(f"right at {j} is ")
        j += 1

    print()
    start_list.dump("start after right copy")
    print()
    right.dump("right after copying from start")
    print()
예제 #5
0
class Dictionary(object):
    def __init__(self, num_buckets=256):
        """Initializes a Map with the given number of buckets."""
        self.map = DoubleLinkedList()
        for i in range(0, num_buckets):
            self.map.push(DoubleLinkedList())

    def hash_key(self, key):
        """Given a key this will create a number and then convert it to
        an index for the aMap's buckets."""
        return hash(key) % self.map.count()

    def get_bucket(self, key):
        """Given a key, find the bucket where it would go."""
        bucket_id = self.hash_key(key)
        return self.map.get(bucket_id)

    def get_slot(self, key, default=None):
        """
        Returns either the bucket and node for a slot, or None, None
        """
        bucket = self.get_bucket(key)

        if bucket:
            node = bucket.begin
            i = 0

            while node:
                if key == node.value[0]:
                    return bucket, node
                else:
                    node = node.next
                    i += 1

        # fall through for both if and while above
        return bucket, None

    def get(self, key, default=None):
        """Gets the value in a bucket for the given key, or the default."""
        bucket, node = self.get_slot(key, default=default)
        return node and node.value[1] or node

    def set(self, key, value):
        """Sets the key to the value, replacing any existing value."""
        bucket, slot = self.get_slot(key)

        if slot:
            # the key exists, replace it
            slot.value = (key, value)
        else:
            # the key does not, append to create it
            bucket.push((key, value))

    def delete(self, key):
        """Deletes the given key from the Map."""
        bucket = self.get_bucket(key)
        node = bucket.begin

        while node:
            k, v = node.value
            if key == k:
                bucket.detach_node(node)
                break

    def list(self):
        """Prints out what's in the Map."""
        bucket_node = self.map.begin
        while bucket_node:
            slot_node = bucket_node.value.begin
            while slot_node:
                print(slot_node.value)
                slot_node = slot_node.next
            bucket_node = bucket_node.next
예제 #6
0
class Dictionary(object):
    def __init__(self, num_buckets=256):
        self.map = DoubleLinkedList()
        for i in range(0, num_buckets):
            self.map.push(DoubleLinkedList())

    def hash_key(self, key):
        """
		Takes key and creates number and index for a map's buckets.

		The hash() method returns the hash value of an object if it has one. Hash values are just integers which are used to compare dictionary keys during a dictionary lookup quickly
		"""

        return hash(key) % self.map.count()

    def get_bucket(self, key):
        """
		Return bucket given a key
		"""

        bucket_id = self.hash_key(key)

        return self.map.get(bucket_id)

    def get_slot(self, key, default=None):
        """
		Returns bucket and node for slot
		"""

        bucket = self.get_bucket(key)

        if bucket:
            node = bucket.begin

            i = 0

            while node:
                if key == node.value[0]:
                    return bucket, node
                else:
                    node = node.next
                    i += 1

        # fall through for both if and while
        return bucket, None

    def get(self, key, default=None):
        """
		Gets value in bucket for given key
		"""
        bucket, node = self.get_slot(key, default=default)

        return node and node.value[1] or node

    def set(self, key, value):
        """
		Sets ket to the value, replacing existing value

		This returns the last DLL and sets the value at the end for a new entry

		For an existing entry it finds the node within the list and replaces it with the tuple
		"""

        bucket, slot = self.get_slot(key)

        if slot:
            slot.value = (key, value)
        else:
            bucket.push((key, value))

    def delete(self, key):
        """
		Delete given key from map
		"""

        bucket = self.get_bucket(key)

        node = bucket.begin

        while node:
            k, v = node.value
            if key == k:
                bucket.detach_node(node)
                break

    def list(self):
        """
		Print out what's in Map
		"""

        bucket_node = self.map.begin

        while bucket_node:
            slot_node = bucket_node.value.begin

            while slot_node:
                print(slot_node.value)
                slot_node = slot_node.next

            bucket_node = bucket_node.next
class Dictionary(object):
    def __init__(self, num_buckets=256):
        """Initializes a Map with the given number of buckets."""
        self.map = DoubleLinkedList()
        for i in range(0, num_buckets):
            self.map.push(DoubleLinkedList())

    def hash_key(self, key):
        """Given a key this will create a number and then convert it to
        and index for the Map's buckets."""
        return hash(key) % self.map.count()

    def get_bucket(self, key):
        """Given a key, find the bucket where it would go."""
        bucket_id = self.hash_key(key)
        return self.map.get(bucket_id)

    def get_slot(self, key, default=None):
        """Returns either the bucket and node for a slot, or None, None"""
        bucket = self.get_bucket(key)

        if bucket:
            node = bucket.begin
            i = 0

            while node:
                if key == node.value[0]:
                    return bucket, node
                else:
                    node = node.next
                    i += 1

        # fall through for both if and while above
        return bucket, None

    def get(self, key, default=None):
        """Gets the value in a bucket for a given key, or the default."""
        bucket, node = self.get_slot(key, default=default)
        return node and node.value[1] or node

    def set(self, key, value):
        """Sets the key to the value, replacing any existing value."""
        bucket, slot = self.get_slot(key)

        if slot:
            # the key exists, replace it
            slot.value = (key, value)
        else:
            # the key does not, append to create it
            bucket.push((key, value))

    def delete(self, key):
        """Deletes the given key from the Map."""
        bucket = self.get_bucket(key)
        node = bucket.begin

        while node:
            k, v = node.value
            if key == k:
                bucket.detach_node(node)
                break

    def list(self):
        """Print out what's in the Map."""
        bucket_node = self.map.begin

        while bucket_node:
            slot_node = bucket_node.value.begin
            while slot_node:
                print(slot_node.value)
                slot_node = slot_node.next
            bucket_node = bucket_node.next
예제 #8
0
class Dictionary(object):
    def __init__(self,
                 num_buckets=256):  # set number of bucktes to 256 ( 2 ** 8)
        """Initializes a Map with the given number of buckets."""
        self.map = DoubleLinkedList(
        )  # self.map is DoubleLinkedList() with it's methods
        for i in range(0, num_buckets):
            self.map.push(DoubleLinkedList(
            ))  # now the parent map-dllist contains 256 child dllists

    def hash_key(self, key):
        """Given a key this will create a number and then convert it to
        an index for the aMap's buckets."""
        return hash(key) % self.map.count(
        )  # create an index for a key  - try print(states.hash_key('NY')) in test_dictionary.py

    def get_bucket(self, key):
        """Given a key, find the bucket where it would go."""
        bucket_id = self.hash_key(
            key)  # get the index of the bucket we want to access
        return self.map.get(
            bucket_id
        )  # get the bucket (parent dllist) at the given id (created with hash_key)

    def get_slot(self, key, default=None):
        """
        Returns either the bucket and node for a slot, or None, None
        """
        bucket = self.get_bucket(
            key)  # find a bucket (get the index of a bucket)

        if bucket:  # if bucket exists
            node = bucket.begin  # set node to the begin of the parent dllist
            i = 0  # what for?

            while node:  # traverse the parent dllist
                if key == node.value[0]:  # if key equals key stored in a node
                    return bucket, node  # return dllist and key-value pair (node)
                else:  # if not, go further
                    node = node.next
                    i += 1

        # fall through for both if and while above
        return bucket, None

    def get(self, key, default=None):
        """Gets the value in a bucket for a given key, or the default."""
        bucket, node = self.get_slot(
            key, default=default
        )  # get the right bucket (parent dllist) and the right node (key-value pair)
        return node and node.value[1] or node  # return key-value pair

    def set(self, key, value):
        """Sets the key to the value, replacing any existing value."""
        bucket, slot = self.get_slot(
            key)  # find a bucket and a slot at/inside this bucket

        if slot:
            # the key exists, replace it
            slot.value = (key, value)
        else:
            # the key does not, append to create it
            bucket.push((key, value))

    def delete(self, key):
        """Deletes the given key from the Map."""
        bucket = self.get_bucket(
            key)  # find a bucket (get the index of a bucket)
        node = bucket.begin  # we need to go through buckets

        while node:  # traverse the parent dllist
            k, v = node.value  # key-value pair set to the value of te node, key-value pair of the node
            if key == k:  # if key matches node's key
                bucket.detach_node(
                    node)  # detach the node from the parent dllist
                break  #stop

    def list(self):
        """Prints out what's in the Map."""
        bucket_node = self.map.begin  # start at the beginning of the parent dllist
        while bucket_node:  # traverse the parent dllist
            slot_node = bucket_node.value.begin  # we need to access a child dllist
            while slot_node:  # traverse a child dllist
                print(
                    slot_node.value
                )  # prints the key-value pair stored inside a slot, which is a node of a child dllist
                slot_node = slot_node.next  # go further inside a child dllist
            bucket_node = bucket_node.next  # go further inside the parent dllist
예제 #9
0
class Dictionary(object):
    def __init__(self, num_buckets=256):
        """Inicjalizuje mapę z daną liczbą wiaderek"""
        self.map = DoubleLinkedList()
        for _ in range(0, num_buckets):
            self.map.push(DoubleLinkedList())

    def hash_key(self, key):
        """Dla danego klucza utworzy liczbę i przekonwertuje ją na
        indeks dla wiaderek mapy"""
        return hash(key) % self.map.count()

    def get_bucket(self, key):
        """Dla danego klucza znajduje wiaderko, w którym powinien być umieszczony"""
        bucket_id = self.hash_key(key)
        return self.map.get(bucket_id)

    def get_slot(self, key, default=None):
        """Zwraca wiaderko i węzeł dla slotu albo None, None"""
        bucket = self.get_bucket(key)
        if bucket:
            node = bucket.begin
            i = 0
            while node:
                if key == node.value[0]:
                    return bucket, node
                else:
                    node = node.next
                    i += 1
        # Przechodzi zarówno przez if, jak i while powyżej
        return bucket, None

    def get(self, key, default=None):
        """Pobiera wartość z wiaderka dla danego klucza lub wartość domyślną"""
        bucket, node = self.get_slot(key, default=default)
        return node and node.value[1] or node

    def set(self, key, value):
        """Ustawia wartość dla klucza, zastępując istniejącą wartość"""
        bucket, slot = self.get_slot(key)
        if slot:
            # Jeśli klucz istnieje, zastępuje go
            slot.value = (key, value)
        else:
            # Jeśli klucz nie istnieje, dodaje go
            bucket.push((key, value))

    def delete(self, key):
        """Usuwa dany klucz z mapy"""
        bucket = self.get_bucket(key)
        node = bucket.begin
        while node:
            k, v = node.value
            if key == k:
                bucket.detach_node(node)
                break

    def list(self):
        """Wypisuje, co znajduje się w mapie"""
        bucket_node = self.map.begin
        while bucket_node:
            slot_node = bucket_node.value.begin
            while slot_node:
                print(slot_node.value)
                slot_node = slot_node.next
            bucket_node = bucket_node.next
예제 #10
0
class Dictionary(object):
	def __init__(self, num_bucket = 256):
		self.map = DoubleLinkedList()
		for i in range(0, num_bucket):
			self.map.push(DoubleLinkedList())

	"""takes a key, convert it to number and get bucket id it will belong to"""
	def hash_key(self, key):
		return hash(key) % self.map.count()

	def get_bucket(self, key):
		bucket_id = self.hash_key(key)
		return self.map.get(bucket_id)

	def get_slot(self, key, default = None):

		"""
		return either a bucket and a node fro the slot , or None, None
		"""
		bucket = self.get_bucket(key)

		if bucket:
			node = bucket.begin
			i=0

			while node:
				if key == node.value[0]:
					return bucket, node
				else :
					node = node.next
					i+=1

		#fall through both if and while above
		return bucket, None

	def get(self, key, default = None):
		bucket, node = self.get_slot(key, default = default)
		return node and node.value[1] or node


	def set(self, key, value):
		bucket, slot = self.get_slot(key)

		if slot:
			slot.value = (key, value)
		else:
			bucket.push((key, value))

	def delete(self, key):
		bucket = self.get_bucket(key)
		node = bucket.begin

		while node:
			k, v = node.value
			if key == k:
				bucket.detach_node(node)
				break

	def list(self):
		bucket_node = self.map.begin
		while bucket_node:
			slot_node = bucket_node.value.begin
			while slot_node:
				print(slot_node.value)
				slot_node = slot_node.next
			bucket_node = bucket_node.next
예제 #11
0
class Dictionary(object):
    """
    python字典的数据结构,用双链表来实现
    {bucket0,bucket1,bucket2,...,bucket256}
    每个bucket也是一个双链表 [key<->value0<->value1<->value2<->...]
    every bucket is a dllist
    """
    def __init__(self, num_buckets=256):
        """Initializes a Map with the given number of buckets."""
        self.map = DoubleLinkedList()
        for i in range(num_buckets):
            self.map.push(DoubleLinkedList())

    def hash_key(self, key):
        """Given a key this will create a # and then convert it to an index for the
        aMap's buckets.
        给一个键,返回这个键对应的bucket的索引值在map里边"""
        return hash(key) % self.map.count()

    def get_bucket(self, key):
        """输入一个键,返回一个包含键值对的节点bucket"""
        bucket_id = self.hash_key(key)
        return self.map.get(bucket_id)

    def get_slot(self, key, default=None):
        """
        Returns either the bucket and node for a slot, or None, None
        插槽
        """
        # an instance of bucket implemented by dllist
        bucket = self.get_bucket(key)

        if bucket:
            node = bucket.begin
            i = 0

            while node:
                if key == node.value[0]:
                    return bucket, node
                else:
                    node = node.next
                    i += 1

        return bucket, None

    def get(self, key, default=None):
        """Gets the value in a bucket for the given key, or the default."""
        bucket, node = self.get_slot(key, default=default)
        return node and node.value[1] or node

    def set(self, key, value):
        """
        字典dict的set方法实现
        Sets the key to the value, replacing any existing value."""
        bucket, slot = self.get_slot(key)

        if slot:
            # the key exists, replace it
            slot.value = (key, value)
        else:
            # the key does not, append to create it
            bucket.push((key, value))

    def delete(self, key):
        """Deletes the given key from the Map."""
        bucket = self.get_bucket(key)
        node = bucket.begin

        while node:
            k, v = node.value
            if key == k:
                bucket.detach_node(node)
                break

    def list(self):
        """Prints out what's in the Map."""
        bucket_node = self.map.begin
        while bucket_node:
            slot_node = bucket_node.value.begin
            while slot_node:
                print(slot_node.value)
                slot_node = slot_node.next
            bucket_node = bucket_node.next
예제 #12
0
class Dictionary(object):
    def __init__(self, num_buckets=256):
        """Initializeds a Map with the given numbers of buckets"""
        self.map = DoubleLinkedList()
        # use map as dictory container. It's actually a DLL
        for i in range(0, num_buckets):
            # this DLL has 256 slots/buckets
            self.map.push(DoubleLinkedList())
            # put 256 DLL inside this map DLL

    def hash_key(self, key):
        """Given a key this will create a number and then convert it to an index for the aMap's buckets."""
        # transfer the "word key" to a "number key" using hash() function
        return hash(key) % self.map.count()

    def get_bucket(self, key):
        """Given a key, find the bucket where it would go."""
        bucket_id = self.hash_key(key)
        # return the number key
        return self.map.get(bucket_id)
        # using the number key, search through the map DLL and get the DLL(bucket) we need

    def get_slot(self, key, default=None):
        # return value is the bucket and node(slot) to locate.
        """Returns either the bucket and node for a slot, or None, None"""
        bucket = self.get_bucket(key)
        # using the key, through number key, get the reference to the DLL(bucket) we need

        if bucket:
            # make sure the bucket is not NULL? (Even it's a empty bucket DLL)
            node = bucket.begin
            # by default, will point to the first node
            i = 0

            # searching through this bucket DLL and find the node of same key. If
            while node:
                # as far as node is not empty, inside will be tuples... (key, value)
                if key == node.value[0]:
                    # if key is same as tuple's first key
                    return bucket, node
                    # this is the node(tuple) we need. return current DLL(bucket) and Node(tuple)
                else:
                    node = node.next
                    # else, search on the next node
                    i += 1

        # fall through for both if and while above
        return bucket, None
        # security. When it will happen?

    def get(self, key, default=None):
        """Gets the value in a bucket for a given key, or the default."""
        bucket, node = self.get_slot(key, default=default)
        return node and node.value[1] or node

    def set(self, key, value):
        """Sets the key to the value, replacing and existing value."""
        bucket, slot = self.get_slot(key)

        if slot:
            # the key exists, replace it
            slot.value = (key, value)
        else:
            # the key does not, append to create it
            bucket.push((key, value))

    def delete(self, key):
        """Deletes the given key from the Map."""
        bucket = self.get_bucket(key)
        node = bucket.begin

        while node:
            k, v = node.value
            if key == k:
                bucket.detach_node(node)
                break

    def list(self):
        """Prints out what's in the Map."""
        bucket_node = self.map.begin
        while bucket_node:
            slot_node = bucket_node.value.begin
            while slot_node:
                print(slot_node.value)
                slot_node = slot_node.next
            bucket_node = bucket_node.next
예제 #13
0
class Dictionary(object):
    def __init__(self, num_buckets=256):
        """Initializes a Map with the given number of buckets."""
        self.map = DoubleLinkedList()  # create new dllist
        # Create a new dllist for each bucket in the map
        for i in range(0, num_buckets):
            self.map.push(DoubleLinkedList())

    def hash_key(self, key):
        """Given a key this will create a number and then convert it to
        an index for the aMap's buckets."""
        # uses a key to get a unique integer, modulus to get the index
        return hash(key) % self.map.count()

    def get_bucket(self, key):
        """Given a key, find the bucket where it would go."""
        # gets index for a key and assigns it to a bucket
        bucket_id = self.hash_key(key)
        # uses index to get the value of the bucket (which is a dllist node)
        return self.map.get(
            bucket_id)  # calls the dllist get() function! OMG!!

    def get_slot(self, key, default=None):
        """
        Returns either the bucket and node for a slot, or None, None
        """
        # gets ref to the slot dllist for a given key
        bucket = self.get_bucket(key)  # slot not bucket right?
        # if the slot in the bucket is not None
        if bucket:
            # initialize to first node in the slot dllist
            node = bucket.begin  # set to first node
            i = 0
            # traverse the slot dllist & check for keys existance
            while node:
                # if the key matches the first element of the key/value tuple
                if key == node.value[0]:
                    return bucket, node  # return the bucket and a ref to the slot / node
                else:
                    node = node.next
                    i += 1  # not sure what this is for...
        # fall through for both if and while above
        return bucket, None  # if key isn't already in the list

    def get(self, key, default=None):
        """Gets the value in a bucket for the given key, or the default."""
        # gets the bucket and slot for a given key
        bucket, node = self.get_slot(key, default=default)
        # ternary operation; if there's a node it returns
        # it's value, if it exists, else the default (None)
        return node and node.value[1] or default

    def set(self, key, value):
        """Sets the key to the value, replacing any existing value."""
        # gets the bucket and slot for a new key/value pair
        bucket, slot = self.get_slot(key)

        if slot:
            # the key exists, replace it
            slot.value = (key, value)
        else:
            # the key does not, append to create it
            bucket.push((key, value))

    def delete(self, key):
        """Deletes the given key from the Map."""
        # gets the bucket (slot) for the key to be removed
        bucket = self.get_bucket(key)
        node = bucket.begin
        # traverse the slot dllist
        while node:
            # unpack the tuple to get the key for comparison
            k, v = node.value
            # check if the keys match
            if key == k:
                # if so, remove the node and exit the loop
                bucket.detach_node(node)
                break
            else:  # otherwise, keep going
                node = node.next

    def list(self):
        """Prints out what's in the Map."""
        # start at the first node of the map
        bucket_node = self.map.begin
        # iterate over the buckets
        while bucket_node:
            # get the first node of the slot list in the given bucket
            slot_node = bucket_node.value.begin
            # iterate through the slot list
            while slot_node:
                # print the value and get the next node
                print(slot_node.value)
                slot_node = slot_node.next
            # get the next bucket
            bucket_node = bucket_node.next