Exemple #1
0
def main():
  testHashToIndex()
  print("Starting with empty hash table")
  hash = HashTable()
  hash.put("A key", "a value")
  assert hash.get("A key") == "a value"
  assert hash.get("A key") != "another value"
    def _getLocations( self ):
        table = HashTable(10)

        # Add locations to hash table
        with open( 'data/locations.csv' ) as file:
            locationData = csv.reader( file, delimiter=',' )
            # Iterate through locations
            # Time Complexity: O(n)
            for row in locationData:
                location = Location( row[0], row[1], row[2] )
                # Add location to hash table of locations
                table.put( int( location.id ), location )

        return table
Exemple #3
0
class Node(object):
    def __init__(self, location):
        self.edges = HashTable(10)
        self.location = location

    #Time Complexity: O(n) where n is the number of edges
    def addEdge(self, edge):
        self.edges.put(int(edge.id), edge)

    #Time Complexity: O(n) where n is the number of edges
    def findEdge(self, id):
        return self.edges.get(id)

    #Time Complexity: O(n) where n is the number of edges
    def getDistance(self, location):
        return self.edges.get(location.id).weight
Exemple #4
0
class Graph(object):
    def __init__(self):
        self.nodes = HashTable(10)

    # Add a vertex to the graph
    # Time Complexity: O(n)
    def addNode(self, location):
        self.nodes.put(int(location.id), Node(location))

    # Add edge between two nodes bidirectionally
    # Time Complexity: O(n)
    def addWeightedEdge(self, origin, terminus, weight):
        originEdge = Edge(origin, weight)
        terminusEdge = Edge(terminus, weight)
        self.nodes.get(origin.id).addEdge(terminusEdge)
        self.nodes.get(terminus.id).addEdge(originEdge)

    # Get id of a vertex at a location
    # Time Complexity: O(n)
    def getNode(self, location):
        return self.nodes.get(location.id)

    # Get first node returned by location name: O(n)
    def getNodeByAddress(self, address):
        for node in self.nodes.getAll():
            if (node.location.address == address):
                return node

    # Get distance between two lcoations
    def getDistanceBetween(self, origin, terminus):
        return self.nodes.get(origin.id).getDistance(terminus)

    # Get nearest neighbor of a location
    # Returns the closest location to the origin
    # Time Complexity: O(n * m)
    def getNearestNeighbor(self, origin, group):
        resultEdges = []
        originNode = self.getNodeByAddress(origin.address)
        originEdges = originNode.edges.getAll()
        for location in group:
            for edge in originEdges:
                if location == edge.location:
                    resultEdges.append(edge)

        nearestNeighbor = min(resultEdges, key=lambda x: x.weight)

        return nearestNeighbor.location
 def _getPackages( self ):
     packages = HashTable(10)
     with open('data/packageFile.csv') as file:
         packageData = csv.reader( file, delimiter = ',' )
         for row in packageData:
             package = Package(
                 row[0],
                 row[1],
                 row[2],
                 row[3],
                 row[4],
                 row[5],
                 row[6],
                 row[7]
             )
             package.setLocation( self.getLocationByAddress( row[1] ) )
             packages.put( package.id, package )
     return packages
Exemple #6
0
class test_hash(unittest.TestCase):

	def setUp(self):
		self.hash = HashTable(11)

	def test_put(self):
		self.hash.put("Lindsey Raymond", "9786217554")
		self.assertEqual(self.hash.keys[3], "Lindsey Raymond")
		self.assertEqual(self.hash.data[3], "9786217554")

	def test_get(self):
		self.assertEqual(self.hash.get("Lindsey Raymond"), "9786217554")

	def test_size(self):
		self.assertEqual(self.hash.length, 11)

	def test_get(self):
		self.hash["James Hayward"] = "123456789"
		self.hash.put("Lindsey Raymond", "9786217554")
		self.assertEqual(self.hash["Lindsey Raymond"], self.hash.get("Lindsey Raymond"))
		self.assertEqual(self.hash["James Hayward"], "123456789")
Exemple #7
0
class Phonebook:

	def __init__(self):
		#connect to permanent storage
		self.create_flag = False
		self.delimiter = '|'
		self.storage = "permanent_data.txt"
		self.database = HashTable(5479)
		#call function to read existing data into hash table
		self._import_data()
	

	def _read_lines(self):
		with open(self.storage, 'r') as old_data:
			for row in old_data:
				if not row.startswith("#"):
					yield row

	def _import_data(self):
		for row in self._read_lines():
			if row.startswith("~"):
				self.create()
			else:
				name = row.split(self.delimiter)[0]
				number = row.split(self.delimiter)[-1]
				self.database[name] = number

	def add(self, name, number):
		#print(self.database.hashkeys)
		if name not in set(self.database.hashkeys):
			self.database[name] = number
		else:
			raise KeyError("Value already exists")


	def remove(self, name):
		self.database.put(name, None)
		self.database.hashkeys[self.database.hashkeys.index(name)] = None

	def change(self, name, number):
		if name in set(self.database.hashkeys):
			self.database[name] = number
		else:
			raise KeyError("Value does not exist")

	def lookup(self, name):
		try:
			return self.database[name]
		except:
			raise KeyError("Value does not exist")

	def reverse_lookup(self, number):
		#Note that this will be slow
		try:
			location = self.database.data.index(number)
			return self.database.hashkeys[location]
		except:
			raise LookupError("Value does not exist")

	def create(self):
		self.create_flag = True

	def save(self):
		with open(self.storage, 'w') as txt_file:
			txt_file.write("#permanent storage file\n")
			if self.create_flag:
				txt_file.write("~CREATED\n")
			for name in self.database.keys:
				if name != None:
					txt_file.write(name+"|"+self.database[name]+"\n")


	def check_input_errors(self, args):
		if len(args) == 1:
			raise RuntimeError("Need more input")


	def parse_arguments(self, args):
		self.check_input_errors(args)
		if self.create_flag:
			if args[1] == "add":
				self.add(*args[2:4])
			else:
				result = getattr(self, args[1])(args[2])
		else:
			if args[1] == 'create':
				self.create()
			else:
				raise RuntimeError("Phonebook does not exist")
		self.save()
		return result