def main():
    data = open('dataset.csv')
    H = HashMap(20)
    keys = []
    passenger = None
    for line in data:
        passenger = Passenger(tuple(line.split(',')[1:]))
        keys.append(passenger.key)
        H.insert(passenger)
    for key in keys:
        try:
            print(H.search(key).details[5])
        except:
            print(key + ' not found')
Пример #2
0
    def __init__(self, name=None):
        """Initialize a new System object. This must be run before the system can be used.

        Args:
            name (str): The name of the system

        >>> print __init__(name='sysname')
        """
        if name:
            self._name = name
        else:
            self._name = "Untitled"

        self._v1x = 0.0
        self._v2x = 0.0
        self._v3x = 0.0
        self._v1y = 0.0
        self._v2y = 0.0
        self._v3y = 0.0
        self._v1z = 0.0
        self._v2z = 0.0
        self._v3z = 0.0

        self._nbFunc = 0
        self._combinationRule = 0
        self._genpairs = True
        self._ljCorrection = 0
        self._coulombCorrection = 0
        self._molecules = OrderedDict.OrderedDict()
        self._atomtypes = HashMap.HashMap()
        self._forces = OrderedSet.OrderedSet()
        self._boxVector = []
Пример #3
0
class RatingContainer(object):
    def __init__(self):
        self._playerToRating = HashMap()


    def getRating(self, player) :

        rating = self._playerToRating.getValue(player)
        return rating


    def setRating(self, player, rating) :

        return self._playerToRating.setValue(player, rating)

    
    def getAllPlayers(self) :

        allPlayers = self._playerToRating.getAllKeys()
        return allPlayers

    def getAllPlayersNames(self) :

        allPlayers = self._playerToRating.getAllKeys()
        list = []
        for player in allPlayers :
            list.append(player.getId())
        return list

    
    def getAllRatings(self) :

        allRatings = self._playerToRating.getAllValues()
        return allRatings


    def count(self) :
        return self._playerToRating.count()

    def __iter__(self):
        obj = []
        obj.append(self._playerToRating.getAllKeys())
        obj.append(self._playerToRating.getAllValues())

        return iter(obj)

    
#    def next(self):
#        list = []
#        for player in self.getAllPlayers() :
#            list.append(player)
#        for i in range(self.count()) :
#            if i == self.index :
#                return list[i] 
Пример #4
0
Файл: eel.py Проект: sbst/eel
def main():
    path = get_path()
    if path is None:
        return 1
    os.chdir(path)
    hash_map = HashMap.HashMap()
    for filename in os.listdir(os.getcwd()):
        size = os.path.getsize(filename)
        hash_map.process(size, filename)
    return 0
Пример #5
0
import time
import Reversi
import HashMap
import random
import sys
from playerInterface import *


BOARDSIZE = 8
SEED = 13459
HASHSIZE = 100000
hashTable = HashMap.HashTable(HASHSIZE)
DEADLINE = round(time.time()*1000) + 1000*60*5

class thePunisher(PlayerInterface):

    def __init__(self):
        self._board = Reversi.Board(10)
        self._mycolor = None
        self._name = "The Punisher"
        self._startFlag = 0
        self.deadline = 9999
        self._eval = [[35,-4,0,12,10,10,12,0,-4,35],
                       [-4,-6,1,1,1,1,1,1,-6,-4],
                       [0,0,1,1,1,1,1,1,0,0],
                       [12,1,1,4,3,3,4,1,1,12],
                       [10,1,1,3,2,2,3,1,1,10],
                       [10,1,1,3,2,2,3,1,1,10],
                       [12,1,1,4,3,3,4,1,1,12],
                       [0,0,1,1,1,1,1,1,0,0],
                       [-6,-8,1,1,1,1,1,1,-8,-6],
 def __init__(self, file):
     '''Mètode constructor'''
     self._hashMap = HashMap()
     self.appendText(file)
class HashMapWordFinder(object):
    def __init__(self, file):
        '''Mètode constructor'''
        self._hashMap = HashMap()
        self.appendText(file)

    def appendText(self, file):
        '''Llegeix el fitxer i el desglossa en lí­nies i paraules per lí­nia'''
        try:
            with open(file, 'r') as reader:
                numLine = 1
                t1 = time.clock()
                array = []
                for line in reader.readlines():
                    numWord = 1
                    if (line):
                        for word in line.split():
                            item = word.lower()
                            array.append(item)
                            numWord += 1
                    numLine += 1
                self._hashMap.prepareTable(
                    HashMapWordFinder.nextPrime(len(array)))
                for item in array:
                    self._hashMap.insertWord(TextWord(item, numLine, numWord))
                t2 = time.clock()
                print u"\nS'han insertat les paraules del text a la taula hash. El temps d'inserció ha estat de {} ms.".format(
                    (t2 - t1) * 1000)
        except IOError:
            print "El nom de l'arxiu donat no existeix."

    def findOcurrencesInFile(self, file):
        '''mostra les aparicions de les paraules d'un text en la taula hash'''
        try:
            print u"\nLes aparicions de paraules de {} a la taula hash són:".format(
                file)
            t1 = time.clock()
            with open(file, 'r') as reader:
                for word in reader.read().split():
                    item = word.lower()
                    self._hashMap.findOcurrences(item)
            t2 = time.clock()
            print "El temps de cerca ha estat de {} ms.".format(
                (t2 - t1) * 1000)
        except IOError:
            print "El nom de l'arxiu donat no existeix."

    def showHashData(self):
        '''mostra el nombre de col·lisions de la taula hash, quants elements té la cel·la amb més elements i el percentatge de cel·les buides'''
        print u"\nEl nombre de col·lisions ha estat de", self._hashMap.getCollisionAmount(
        )
        print u"El nombre d'elements en la cel·la de més elements és de", self._hashMap.getMaxElemAmountInSlot(
        )
        print u"El percentatge de cel·les buides és de", self._hashMap.calcEmptyPercentage(
        )

    @staticmethod
    def askFile():
        ''' demana un arxiu'''
        file = raw_input("Entra el nom d'un fitxer (Ex: smallText.txt) --> ")
        return file

    @staticmethod
    def main():
        '''mètode principal de l'aplicació. Crea el cercador, demana a l'usuari el nom d'un text i en ell cerca i mostra les paraules d'un diccionari trobades, a més de mostrar ordenades alfabèticament les paraules i mostrar certes dades de la taula hash'''
        h = HashMapWordFinder(HashMapWordFinder.askFile())
        h.findOcurrencesInFile('dictionary.txt')
        h.showHashData()

    @staticmethod
    def isPrime(n):
        '''retorna si un nombre és primer'''
        return not any(n % i == 0 for i in range(2, n))

    @staticmethod
    def nextPrime(n):
        '''retorna el primer nombre primer a partir del número indicat'''
        found = False
        result = 0
        while not found:
            if HashMapWordFinder.isPrime(n):
                found = True
            else:
                n += 1
        return n
Пример #8
0
    try:
        print(m.find(6))
    except Exeption.NotFoundException:
        print("Item not found")
    try:
        print(m[7])
    except Exeption.NotFoundException:
        print("Item not found")

    print("size of map: " + str(len(m)))
    try:
        m.remove(5)
        print("Item removed")
    except Exeption.NotFoundException:
        print("Item not found")
    try:
        print(m.find(5))
    except Exeption.NotFoundException:
        print("Item not found")

    print("size of map: " + str(len(m)))


if __name__ == "__main__":
    print("\nTESTING BUCKET")
    m = Bucket.Bucket()
    test_map(m)
    print("\nTESTING HASHMAP")
    m = HashMap.HashMap()
    test_map(m)
Пример #9
0
 def __init__(self):
     self._playerToRating = HashMap()
Пример #10
0
import datetime
import Package
import HashMap
import Truck

#This section creates a blank list and takes the data from the csv file and creates instance of the packages which are put into the package list O(N)
packageList = []
with open('PackageSheet.csv', newline='') as csvfile:
    DataReader = csv.reader(csvfile)
    for row in DataReader:
        packageList.append(
            Package.Package(row[0], row[1], row[2], row[3], row[4], row[5],
                            row[6], row[7], 'At Hub', ''))

#This section creates a Hash table that is populated using the package ID as the key and the package itself as the value O(N)
hashTable = HashMap.HashMap()
for package in packageList:
    hashTable.add(int(package.packageID), package)

#This is a dictionary of locations for reference O(1)
locations = {
    '4001 South 700 East': 0,
    '1060 Dalton Ave S': 1,
    '1330 2100 S': 2,
    '1488 4800 S': 3,
    '177 W Price Ave': 4,
    '195 W Oakland Ave': 5,
    '2010 W 500 S': 6,
    '2300 Parkway Blvd': 7,
    '233 Canyon Rd': 8,
    '2530 S 500 E': 9,
Пример #11
0
import HashMap

h = HashMap()
h.add('Bob', '567-8888')
h.add('Ming', '293-6753')
h.add('Ming', '333-8233')
h.add('Ankit', '293-8625')
h.add('Aditya', '852-6551')
h.add('Alicia', '632-4123')
h.add('Mike', '567-2188')
h.add('Aditya', '777-8888')
h.print()		
h.delete('Bob')
h.print()
print('Ming: ' + h.get('Ming'))
print(h.keys())
Пример #12
0
 def __init__(self):
     self._playerToRating = HashMap()
Пример #13
0
def atualizaFipe():
    carsTree = None
    carrosList = []
    carrosMap = {}
    fipeMap = dicionario.HashMap()

    fipeURL = "http://fipeapi.appspot.com/api/1/carros/marcas.json"
    tknzr = WhitespaceTokenizer()

    chromeOptions = webdriver.ChromeOptions(
    )  # seta configs pra nao carregar imagens (aumenta velocidade do crawler)
    prefs = {"profile.managed_default_content_settings.images": 2}
    chromeOptions.add_experimental_option("prefs", prefs)
    chromeOptions.add_argument("--incognito")
    browser = webdriver.Chrome(chrome_options=chromeOptions)

    browser.get(fipeURL)
    page_json = soup(browser.page_source,
                     'html5lib').find("body").find("pre").text
    filename = 'fipe.csv'
    f = open(filename, "w")
    jsonMarcas = json.loads(page_json)
    mapMarcas = dicionario.HashMap()
    mapVeiculos = dicionario.HashMap()
    for marca in jsonMarcas:
        browser.get('http://fipeapi.appspot.com/api/1/carros/veiculos/' +
                    str(marca['id']) + '.json')
        time.sleep(1)
        modelos = soup(browser.page_source,
                       'html5lib').find("body").find("pre").text
        modelos = json.loads(modelos)
        mapMarcas.put(marca["fipe_name"], modelos)
        for modelo in modelos:
            print(modelo)
            modeloNome = tknzr.tokenize(modelo['name'])
            if modeloNome[0].upper() == "GRAND" or (
                    len(modeloNome) > 1 and modeloNome[1].upper()
                    == "LOUNGE") or modeloNome[0].upper() == "XC":
                modeloNome = str(modeloNome[0] + modeloNome[1])
            elif modeloNome[0].upper() == "SANTA":
                modeloNome = str(modeloNome[0] + modeloNome[1][:2])
            else:
                modeloNome = modeloNome[0]
            modeloNome = modeloNome.upper()
            modeloNome = modeloNome.replace("-", "")
            modeloNome = modeloNome.replace("!", "")
            if modelo['fipe_marca'].upper() == 'VW - VOLKSWAGEN':
                modelo['fipe_marca'] = 'VOLKSWAGEN'
            elif modelo['fipe_marca'].upper() == 'GM - CHEVROLET':
                modelo['fipe_marca'] = 'CHEVROLET'
            elif modelo['fipe_marca'] == 'Citro\u00ebn':
                modelo['fipe_marca'] = 'CITROEN'
            elif modelo['fipe_marca'].upper() == 'KIA MOTORS':
                modelo['fipe_marca'] = 'KIA'
            f.write(modelo["fipe_marca"].upper() + "," + str(marca['id']) +
                    "," + modeloNome + "," + modelo["id"] + "\n")

    with open('fipe.csv', 'r') as f:
        reader = csv.reader(f)
        for row in reader:
            fipeMap.put(
                str(row[0]) + str(row[2]),
                str(row[1]) + " " +
                str(row[3]))  #pair(fipeMarca+fipeNome,marcaID+nomeID)

    with open('carros.csv', 'r') as f:
        reader = csv.reader(f)
        for row in reader:
            chave = str(row[1]) + str(row[2]) + str(
                row[3])  #fabricante + modelo + ano
            objId = fipeMap.getObj(
                str(row[1]) + str(row[2])
            )  #guarda objeto com os varios codigos fip para aquele veículo. (vamos precisar iterar ele depois quando formos acessar os dados via selenium)
            car1 = {
                "chave": chave,
                "fabricante": row[1],
                "modelo": row[2],
                "ano": row[3],
                "objID": objId
            }  #tal iteracao é para driblar falta de informacao dos veículos das revendedoras (fipe usa nome completo com especificacoes e as revendedoras nao)
            if carrosList.count(car1) == 0:
                carrosList.append(car1)

    print(len(carrosList))
    print(carrosList)
    i = 0
    filename = "carrosEFipe.csv"  #abe arquivo para escrita
    fw = open(filename, "w")
    for car1 in carrosList:
        i += 1
        print(i)
        for j in range(1, 4, 1):
            for ID in car1['objID'].listValues:
                ID = tknzr.tokenize(str(ID))
                marcaID = ID[0]
                fipeID = ID[1]
                print("\t" + fipeID)
                year = str(car1["ano"]) + "-" + str(j)
                print("\t" + year)
                time.sleep(
                    0.5
                )  # servidor da api tem limite de requisicoes por minuto
                browser.get(
                    "http://fipeapi.appspot.com/api/1/carros/veiculo/" +
                    marcaID + "/" + fipeID + "/" + year + ".json")
                elem = soup(browser.page_source,
                            "html5lib").find("body").find("h1")
                if elem is not None and elem.text == '500 Internal Server Error':
                    continue
                else:
                    break
            if elem is not None and elem.text == '500 Internal Server Error':
                continue
            else:
                carroFipeInfo = soup(browser.page_source,
                                     'html5lib').find("body").find("pre").text
                carroFipeInfo = json.loads(carroFipeInfo)
                preco = tknzr.tokenize(carroFipeInfo["preco"])
                preco = preco[1]
                preco = preco[:len(preco) - 3].replace(".", "")
                print(car1["chave"])
                fw.write(car1["chave"] + "," + preco + "\n")
                break