Ejemplo n.º 1
0
    def edges(self):
        bag = Bag()
        for i in range(0, self._vertex_num):
            for edge in self._adj[i]:
                bag.add(edge)

        return bag
    def process(self, check_in_counters, equipment_area_queue,
                security_check_queue):
        # Customer arrives and chooses the first queue with the
        # shortest length
        time_arrive = self._env.now
        queue_lengths = ([self._len_queue(check_in_counters[i]) for i in
                          range(len(check_in_counters))])
        min_length = min(queue_lengths)
        chosen_counter_id = queue_lengths.index(min_length)
        chosen_counter = (check_in_counters[chosen_counter_id])
        print("[Customer {0}]\tbags: {1},\tArrival time: {"
              "2:.4f}s\tCheck-in counter: {3}").format(self._cust_id,
                                                       self._num_bags,
                                                       time_arrive,
                                                       chosen_counter_id)

        # Customer arrives at queue for service
        service_time = self._service_time()
        request = chosen_counter.request()
        yield request
        yield self._env.timeout(service_time)
        chosen_counter.release(request)
        time_serv = self._env.now
        print("[Customer {0}]\tFinished serving: {1:.4f}s").format(
            self._cust_id, time_serv)
        # The customer has been served and their bags (if any exist) are
        # put on the conveyor.
        for i in range(1, self._num_bags+1):
            bag = Bag(self._env, self._cust_id, i, self._random)
            self._env.process(bag.process(equipment_area_queue,
                                          security_check_queue))
Ejemplo n.º 3
0
    def edges(self):
        bag = Bag()

        for i in range(0, self._vertex_num):
            for edge in self._adj[i]:
                other_vertex = edge.other(i)
                if other_vertex > i:
                    bag.add(edge)

        return bag
Ejemplo n.º 4
0
 def populate_bag(self):
     the_bag = Bag().get_bag()
     the_current_value = the_bag.pop(len(self.letters) // 2)
     self.insert(the_current_value)
     highest_index = len(the_bag) - 1
     for i in range(0, len(the_bag)):
         random_number = Random().randint(0, highest_index)
         the_current_value = the_bag.pop(random_number)
         self.insert(the_current_value)
         highest_index -= 1
Ejemplo n.º 5
0
    def populate_bag(self):
        """Gets the letters from Bag as (letter,points,amount) then populates the tree and tries to get good spread by placing the middle first and then random"""
        the_bag = Bag().get_bag()
        the_current_value = the_bag.pop(len(self.letters) // 2)
        self.insert(the_current_value)
        highest_index = len(the_bag) - 1

        for i in range(0, len(the_bag)):
            random_number = Random().randint(0, highest_index)
            the_current_value = the_bag.pop(random_number)
            self.insert(the_current_value)
            highest_index -= 1
Ejemplo n.º 6
0
def start_game():
    global round_number, players, skipped_turns
    board = Board()
    bag = Bag()
    Settings.dictionary1 = int(
        input(
            "For English Dictionary enter 1 for Romanian Dictionary enter 2: ")
    )
    num_of_players = int(input("\nPlease enter the number of players (2-4): "))
    while num_of_players < 2 or num_of_players > 4:
        num_of_players = int(
            input(
                "This number is invalid. Please enter the number of players (2-4): "
            ))

    print(
        "\nWelcome to Scrabble! Please enter the names of the players below ")
    players = []
    for i in range(num_of_players):
        players.append(Player(bag))
        players[i].set_name(
            input("Please enter player " + str(i + 1) + "'s name: "))

    round_number = 1
    skipped_turns = 0
    current_player = players[0]
    turn(current_player, board, bag)
Ejemplo n.º 7
0
    def __init__(self,d):
##        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
##        self.window.set_size_request(600,650)
##        self.window.set_title("Scrabble")
##        self.statusbar = gtk.Statusbar()
##        self.window.connect("delete_event",self.delete_event)
##        self.window.connect("destroy",self.destroy)
##        
##        self.window.show()
##        self.refresh()
        self.d = d
        self.bag = Bag()
        self.board = Board()
        self.players = []
        self.p1 = Player(raw_input("Player name: "),self.bag,self.d)
        self.p2 = Player("Robot",self.bag,self.d)
        for i in [self.p1,self.p2]:
            self.players.append(i)
        for i in self.players:
            i.newHand()

        while not self.bag.isEmpty():
            for i in self.players:
                print self.board
                print i.name+"'s turn"          
                i.turn()
        for i in self.players:
            print i.name+' '+str(i.score)
Ejemplo n.º 8
0
    def __init__(self, E=None, V=None, In=None, G=None):

        self.G = None
        self.E = None
        self.adj = []
        self.indegree = []

        if E is None and V is None and In is None and G is None:
            raise ValueError("One of E, V, In or G argument must be given.")

        if V is not None:
            if V < 0:
                raise IllegalArgumentException(
                    "Number of vertices must be non-negative.")
            self.V = V
            self.E = 0
            for v in range(self.V):
                self.adj.append(Bag())

        if E is not None:
            if E < 0:
                raise IllegalArgumentException(
                    "Number of Edges must be non-negative.")
            self.E = E

        if In is not None:
            E = In.readInt()
            if E < 0:
                raise IllegalArgumentException(
                    "Number of Edges must be non-negative.")

        if G is not None:
            self.G = G
            self.V = G.V()
Ejemplo n.º 9
0
    def get_bag(self, index):
        if index < len(self.bags):
            bag = self.bags[index]
        else:
            bag = Bag()
            self.bags.append(bag)

        return bag
Ejemplo n.º 10
0
 def __init__(self, name, location, tile):
     self.name = name
     self.bag = Bag()
     self.dialogue = ''
     self.stopped = False
     self.inventory = []
     self.main = None
     self.x = 50
     self.y = 50
     self.height = 60
     self.width = 40
     self.curr_location = location
     self.curr_tile = tile
     self.stance = None
     self.screen_dimensions = None, None
     self.diff = 0
     self.cash = 0
Ejemplo n.º 11
0
 def __init__(self, vertex_num):
     self._vertex_num = vertex_num  # The number of vertices
     self._edge_num = 0  # The number of edges
     self._adj = np.empty(
         vertex_num, dtype=object
     )  # The adjacency list, which stores all the edges (not vertices)
     for i in range(0, vertex_num):
         self._adj[i] = Bag()
Ejemplo n.º 12
0
 def create_fingerprint(self, text):
     words = Dino.extract_words(text)
     good_words = []
     for word in words:
         if word in self.__syn_map:
             good_words.append(word)
     freq_pairs = [(k, len(list(g)))
                   for k, g in groupby(sorted(good_words))]
     bag = Bag(freq_pairs)
     return bag
Ejemplo n.º 13
0
Archivo: 7.py Proyecto: Phil-vP/advent
def doSomething():
    #if __name__== "__main__":

    with open("input.txt") as fp:
        allLines = fp.read().splitlines()

    allBagKeys = []
    allBags = {}
    stativ = "lightred"

    for l in allLines:
        print(l)
        l_sp = l.split(' ')
        source_color = l_sp[0] + l_sp[1]
        print(source_color)

        allBagKeys.append(source_color)

        bag_count = l.count("bag") - 1
        if "no other" in l:
            bag_count = 0
#        print(bag_count)

        children = {}

        for i in range(bag_count):
            child_name = l_sp[5 + i * 4] + l_sp[6 + i * 4]
            children[child_name] = int(l_sp[4 + i * 4])


#            children.append(l_sp[5+i*4] + l_sp[6+i*4] + ": " + l_sp[4+i*4])

#        print(children)

        b = Bag(source_color)
        b.setNachfolgerMap(children)
        allBags[source_color] = b

    for b in allBagKeys:
        allBags[b].calcNachfolgerToBag(allBags)

    print(allBags["shinygold"].getNumber() - 1)
def testCreate():
    b = Bag()
    assert(b.size() == 0)
    assert(b.isEmpty() == True)
    for i in range(-5,5):
        assert(b.search(i) == False)
    for i in range(-10,10):
        assert(b.remove(i) == False)
    for i in range(-10,10):
        assert(b.nrOccurrences(i) == 0)

    it = b.iterator()
    assert(it.valid() == False)
Ejemplo n.º 15
0
 def __init__(self, name, weight):
     self.name = name
     self.weight = weight
     self.inBag = Bag("noBag", 0, 0, 0)
     self.isInBag = False
     self.allowedBags = [] # list of bags that this item can be in
     self.mustBeWith = [] # list of items that must be in the same bag as this item
     self.cantBeWith = [] # list of items that cannot be in the same bad as this item
     self.partnerItems = [] # Mutually exclusive items. Empty if this item does not have a mutually inclusive binary constraint.
     self.partnerBags = [] # the bags that the mutually exclusive items can be in, all arrays of 2 bags
     self.heuristic = 0
Ejemplo n.º 16
0
    def __init__(self, V=None, E=None, In=None):
        """Initializes an empty edge-weighted digraph with {@code V} vertices and {@code E} edges.

        @throws ValueError if {@code V < 0}
        :param V: the number of vertices.
        :param E: the number of edges.
        """
        if V is not None and V < 0:
            raise ValueError(
                "Number of vertices in a Digraph must be nonnegative.")

        if E is not None and E < 0:
            raise ValueError(
                "Number of Edges in a Digraph must be nonnegative.")

        if E is None and V is None and In is None:
            raise ValueError("Invalid ")

        if V is not None and E is None:
            for v in range(V):
                self.adj[v] = Bag()

        if V is not None and E is not None:
            self.V = V
            for v in range(V):
                self.adj[v] = Bag()
            for e in range(E):
                v1 = random.choice(range(self.V))
                v2 = random.choice(range(self.V))
                w = random.randint() * 100
                self.addEdge(DirectedEdge(v1, v2, w))

        self.E = 0

        self.indegree = []
        self.adj = []

        if In is not None:
            pass
Ejemplo n.º 17
0
 def _crossover(self, p1, p2):
     crossoverType = self.nItems  # uniform cross over
     c = []
     for i in range(2):
         genes = []
         for i in range(crossoverType):
             x = r.choice([p1, p2])
             g = x.getGenes()
             genes.append(g[i])
         child = Bag(genes=genes, limit=self.limit)
         # Check legality, otherwise retun random parent
         if child.totalWeight < self.limit:
             c.append(child)
             #print('yay')
         else:
             c.append(x)
             #print('fail')
     return c
Ejemplo n.º 18
0
def parse_a_page(url):
    bags = BagSet()
    try:
        response = urllib2.urlopen(url)
        html_source = response.read()
        soup = BeautifulSoup(html_source)
        divs = soup.findAll('div', attrs={'class': 'details'})
    except:
        print '[ERROR][read source code]', sys.exc_info()
        return bags
    
    for div in divs:
        div_str = str(div)
        div_str = div_str.replace('\n', '')
        div_str = re.sub('\s+', ' ', div_str)
        try:
            bags.add( Bag(div_str) )
        except:
            print '[ERROR][create bag obj]', sys.exc_info()

    return bags
Ejemplo n.º 19
0
    def read_file(file_name):
        file = open(file_name, "r")
        vertex_num = int(file.readline())
        edge_num = int(file.readline())

        # Build a graph
        graph = DirectedGraph(vertex_num)
        graph._vertex_num = vertex_num
        graph._adj_list = np.empty(vertex_num, dtype=object)
        for i in range(0, vertex_num):
            graph._adj_list[i] = Bag()

        graph._vertex_num = vertex_num
        lines = file.readlines()
        for line in lines:
            data = line.split(" ")
            start = int(data[0])
            end = int(data[1])

            graph._add_edge(start, end)

        file.close()
        return graph
Ejemplo n.º 20
0
    def _randomPoulation(self):
        knapsacks = []
        for k in range(self.populationSize):
            genom = [0] * self.nItems
            indexList = list(range(self.nItems))
            total = 0

            for i in range(self.nItems):
                # Choose item by index
                x = r.choice(indexList)
                indexList.remove(x)
                item = self.items[x]
                a = r.choice([True, False])
                if total + item.getWeight() > self.limit:
                    a = False
                elif a:
                    total += item.getWeight()
                gene = Item(weight=item.getWeight(),
                            value=item.getValue(),
                            active=a)
                genom[x] = gene
            e = Bag(genes=genom, limit=self.limit)
            knapsacks.append(e)
        return knapsacks
def testQuantity():
    b = Bag()
    print('Adding')
    for i in range(10, 0, -1):
        print(i)
        for j in range(-30000, 30000, i):
            b.add(j)

    assert(b.size() == 175739)
    assert(b.nrOccurrences(-30000) == 10)
    it = b.iterator()
    print('Dimension: ', b.size())
    print('Iterator')
    assert(it.valid() == True)
    for i in range(0, b.size()):
        it.next()
	
    it.first()
    print('Iterator 2')
    count = 0
    while it.valid():
        if count % 1000 == 0:
            print('  ', count)
        e = it.getCurrent()
        assert(b.search(e) == True)
        assert(b.nrOccurrences(e) > 0)
        it.next()
        count += 1
	
    assert(it.valid() == False)
    print('Remove')
    for i in range(0, 10):
        print(i)
        for j in range(40000, -40000-1, -1):
            b.remove(j)
	
    assert(b.size() == 0)
Ejemplo n.º 22
0
 def __init__(self, vertex_num):
     self._vertex_num = vertex_num
     self._edge_num = 0
     self._adj_list = np.empty(vertex_num, dtype=object)
     for i in range(0, vertex_num):
         self._adj_list[i] = Bag()
Ejemplo n.º 23
0
    def __init__(self, roomData, itemData):
        self.bag = Bag()
        self.stuff = list()
        self.roomNames = []
        self.rooms = list()
        self.necklacePlaced = False
        self.dollPlaced = False
        self.journalPlaced = False

        for item in itemData:
            self.stuff.append(
                Stuff(itemData[item]["name"], itemData[item]["description"],
                      itemData[item]["availableVerbs"],
                      itemData[item]["relatedItems"]))

        for idx, room in enumerate(roomData):
            self.roomNames.append(roomData[room]["roomName"])

            self.roomItems = []
            for roomItem in roomData[room]["item"]:
                for item in self.stuff:
                    if item.name == roomItem:
                        self.roomItems.append(item)

            #adding hidden items
            self.hiddenItems = []
            if hasattr(roomData[room], "hidden"):
                for roomHiddenItem in ["hidden"]:
                    for item in self.stuff:
                        if item.name == roomHiddenItem:
                            self.hiddenItems.append(item)

            self.rooms.append(
                Room(roomData[room]["roomName"], self.roomItems, True,
                     self.hiddenItems))
            if self.roomNames[idx] == "Front Yard":
                self.initialRoom = self.rooms[idx]

        for idx, room in enumerate(roomData):
            neighbors = []
            neighborDirections = {}

            if roomData[room]["neighbors"]["north"] in self.roomNames:
                for neighbor in enumerate(self.rooms):
                    if neighbor[1].name == roomData[room]["neighbors"][
                            "north"]:
                        neighbors.append(neighbor[1])
                        neighborDirections.update({"north": neighbor[1]})
            if roomData[room]["neighbors"]["south"] in self.roomNames:
                for neighbor in enumerate(self.rooms):
                    if neighbor[1].name == roomData[room]["neighbors"][
                            "south"]:
                        neighbors.append(neighbor[1])
                        neighborDirections.update({"south": neighbor[1]})
            if roomData[room]["neighbors"]["east"] in self.roomNames:
                for neighbor in enumerate(self.rooms):
                    if neighbor[1].name == roomData[room]["neighbors"]["east"]:
                        neighbors.append(neighbor[1])
                        neighborDirections.update({"east": neighbor[1]})
            if roomData[room]["neighbors"]["west"] in self.roomNames:
                for neighbor in enumerate(self.rooms):
                    if neighbor[1].name == roomData[room]["neighbors"]["west"]:
                        neighbors.append(neighbor[1])
                        neighborDirections.update({"west": neighbor[1]})

            self.rooms[idx].setNeighbors(neighbors)
            self.rooms[idx].neighborDirections = neighborDirections

            self.rooms[idx].setLongDescription(
                roomData[room]["longDescription"])
            self.rooms[idx].setShortDescription(
                roomData[room]["shortDescription"])
        self.currentRoom = self.initialRoom
Ejemplo n.º 24
0
    def _depth_first_search(self, graph, source):
        self._marked[source] = True
        for neighbor in graph.adj(source):
            if not self._marked[neighbor]:
                self._depth_first_search(graph, neighbor)

    # Check if a vertex is reachable from the source
    def reachable(self, vertex):
        return self._marked[vertex]


if __name__ == "__main__":
    argc = len(argv)
    file_name = argv[1]
    sources = Bag()
    for i in range(2, argc):
        sources.add(int(argv[i]))

    graph = DirectedGraph.read_file(file_name)
    vertex_num = graph.vertex_num()
    path = DFSDirectedGraph(graph)
    path.search_mulitple_sources(graph, sources)

    print("The graph: ")
    print(graph)

    for vertex in range(0, vertex_num):
        if path.reachable(vertex):
            print(vertex, end=" ")
Ejemplo n.º 25
0
def main():
    b = Bag()
    bagIterator = b.iterator()
    b.add(4)
    b.add(11)
    b.add(4)
    b.add(77)
    b.add(8)
    printBag(bagIterator)
    print(b.frequences)
Ejemplo n.º 26
0
 def load_fingerprint(filepath):
     fp = Bag()
     fp.load(filepath)
     return fp
Ejemplo n.º 27
0
def readFile():
    file = sys.argv[1]
    dataFile = open(file, 'r')
    state = -1
    """
    State 0:
        Adding variables
    State 1:
        Adding values
    State 2:
        fitting limits
    State 3:
        unary inclusive
    State 4:
        unary exclusive
    State 5:
        binary equals
    State 6:
        binary not equals
    State 7:
        binary simultaneous
    """

    for line in dataFile:
        if line[0] == '#':
            state += 1
            #print "State change to: ", state
        else:
            if state == 0:
                lineData = line.split(" ")
                itemList.append(Item(lineData[0], int(lineData[1])))
            elif state == 1:
                lineData = line.split(" ")
                bagList.append(Bag(lineData[0], int(lineData[1]), 0, 0))
            elif state == 2:
                lineData = line.split(" ")
                fittingLimits[0], fittingLimits[1] = (int(removeNonAscii(lineData[0])), int(removeNonAscii(lineData[1]))) #Dumb depackaging thing because python yay
            elif state == 3:
                lineData = line.split(" ")
                cleanedLineData = []
                for term in lineData: # Clean each term of non-ascii formatting characters
                    cleanedLineData.append(removeNonAscii(term))
                for item in itemList: # For each item in our item list
                    if item.name == cleanedLineData[0]: # If we've found the item that this line is describing
                        for nameOfBag in cleanedLineData: #For each element in the cleaned line data. Of course first element will never be the case we want. Looking for bag names.
                            for bag in bagList: # for each of our bags
                                if bag.name == nameOfBag: #If any of our bags are of the name of the item we are setting up inclusive unary constraints:
                                    item.allowedBags.append(bag) #Add that bag to the list of acceptable bags.'
                                    #print "List of bags that ", item.name, "is exclusively allowed in so far:"
                                    #for g in item.allowedBags:
                                        #print g.name

            elif state == 4:
                lineData = line.split(" ")
                cleanedLineData = []

                bagsToAdd = []

                for bagInit in bagList:
                    bagsToAdd.append(bagInit)

                for term in lineData: # Clean each term of non-ascii formatting characters
                    cleanedLineData.append(removeNonAscii(term))
                for item in itemList: # For each item in our item list
                    if item.name == cleanedLineData[0]: # If we've found the item that this line is describing
                        for nameOfBag in cleanedLineData: #For each element in the cleaned line data. Of course first element will never be the case we want. Looking for bag names.
                            for bag in bagList: # for each of our bags
                                if bag.name == nameOfBag: #If any of our bags are of the name of the item we are setting up exclusive unary constraints:
                                    if bag in item.allowedBags:
                                        item.allowedBags.remove(bag) #If the bag was listed in unary exclusion AND unary inclusion. Why that would ever happen, IDK, but it happens in one of the given cases. Ugh. Thanks.
                                    bagsToAdd.remove(bag)
                                    #print "Removing ", bag.name , " bag from ", item.name ,"'s pool of possible bags."
                        #print "Bags it's really ok to add for ", item.name
                        for bagsToReallyAdd in bagsToAdd:
                            item.allowedBags.append(bagsToReallyAdd)
                            #print bagsToReallyAdd.name
            elif state == 5: # Binary Equality
                lineData = line.split(" ")

                cleanedLineData = []

                for itemName in lineData:
                    cleanedLineData.append(removeNonAscii(itemName))

                for itemsToCheck in itemList:
                    if itemsToCheck.name in cleanedLineData:
                        for elt in cleanedLineData:
                            for items in itemList:
                                if items.name == elt:
                                    itemsToCheck.mustBeWith.append(items)

            elif state == 6: # Binary Inequality
                lineData = line.split(" ")

                cleanedLineData = []

                for itemName in lineData:
                    cleanedLineData.append(removeNonAscii(itemName))

                for itemsToCheck in itemList:
                    if itemsToCheck.name == cleanedLineData[0]:
                        for itemPartnerToCheck in itemList:
                            if itemPartnerToCheck.name == cleanedLineData[1]:
                                itemsToCheck.cantBeWith.append(itemPartnerToCheck)
                                itemPartnerToCheck.cantBeWith.append(itemsToCheck)
            else: # state == 7:
                lineData = line.split(" ")

                cleanedLineData = []

                for descriptor in lineData:
                    cleanedLineData.append(removeNonAscii(descriptor))

                for itemsToCheck in itemList:
                    if itemsToCheck.name == cleanedLineData[0]:
                        for itemPartnerToCheck in itemList:
                            if itemPartnerToCheck.name == cleanedLineData[1]: # If we have detected partners:
                                itemsToCheck.partnerItems.append(itemPartnerToCheck)
                                itemPartnerToCheck.partnerItems.append(itemsToCheck)
                                bagArray = []
                                for bagsNames in bagList:
                                    if (bagsNames.name == cleanedLineData[2]) or bagsNames.name == cleanedLineData[3]:
                                        bagArray.append(bagsNames)

                                itemsToCheck.partnerBags.append(bagArray)
                                itemPartnerToCheck.partnerBags.append(bagArray)

    verbose = False
    for itemsToCheckBagsAllowed in itemList:
        if len(itemsToCheckBagsAllowed.allowedBags) == 0:
            for allBags in bagList:
                itemsToCheckBagsAllowed.allowedBags.append(allBags)
        if verbose: print "Bags that ", itemsToCheckBagsAllowed.name, " is allowed in:"
        for bagsAllowed in itemsToCheckBagsAllowed.allowedBags:
            if verbose:print bagsAllowed.name
        if verbose:print "Bags that ", itemsToCheckBagsAllowed.name, " must be in a bag with:"
        for bagFriends in itemsToCheckBagsAllowed.mustBeWith:
            if verbose:print bagFriends.name
        if verbose:print "Bags that ", itemsToCheckBagsAllowed.name, " must NOT be in a bag with:"
        for bagEnemies in itemsToCheckBagsAllowed.cantBeWith:
            if verbose:print bagEnemies.name
        for x in range (0, len(itemsToCheckBagsAllowed.partnerItems)):
            if verbose:print itemsToCheckBagsAllowed.name, "'s first binary simultaneous partner is ", itemsToCheckBagsAllowed.partnerItems[x].name,\
                ", and their bags are "
            for partnerBags in itemsToCheckBagsAllowed.partnerBags[x]:
                if verbose:print partnerBags.name

    for bagsToUpdateMinMax in bagList:
        bagsToUpdateMinMax.minItems = fittingLimits[0]
        bagsToUpdateMinMax.maxItems = fittingLimits[1]

    if len(bagList) > 0:
        if verbose: print "Bags can hold between ", bagList[0].minItems, " and ", bagList[0].maxItems, " items, inclusively."
    if verbose: print "Set up complete."
Ejemplo n.º 28
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from Bag import Bag

b = Bag()
b.add(1)
b.add("Leon")
b.add(3.14)
b.remove(1)
for a in b:
	print(a)
print(b.contains(3.14))
print(len(b))
Ejemplo n.º 29
0
class Player:
    """
    Actual player
    """
    def __init__(self, name, location, tile):
        self.name = name
        self.bag = Bag()
        self.dialogue = ''
        self.stopped = False
        self.inventory = []
        self.main = None
        self.x = 50
        self.y = 50
        self.height = 60
        self.width = 40
        self.curr_location = location
        self.curr_tile = tile
        self.stance = None
        self.screen_dimensions = None, None
        self.diff = 0
        self.cash = 0

    def add_pokemon(self, pokemon):
        if len(self.bag.pokemons) == 6:
            self.inventory.append(pokemon)
        else:
            self.bag.add_pokemon(pokemon)
            if self.main is None:
                self.change_main(pokemon)

    def heal(self):
        for pokemon in self.bag.pokemons:
            pokemon.restore()

    def change_main(self, pokemon):
        #pokemon must be in bag
        self.bag.pokemons[0], self.bag.pokemons[self.bag.pokemons.index(pokemon)]=\
            self.bag.pokemons[self.bag.pokemons.index(pokemon)], self.bag.pokemons[0]
        self.main = self.bag.main = pokemon

    def make_corners(self, max_width, max_heigt):
        """
        creatig the moving screen corners of the player using their current location.
        These cornors allow the screen to stop and start following at certain distances from the edge
        """
        self.screen_dimensions = x, y = min(max_width,
                                            self.curr_location.width), min(
                                                max_heigt,
                                                self.curr_location.height)
        x, y = x - 1, y - 1
        left, right = self.curr_tile, self.curr_tile
        while x > 0:
            if left.left is not None:
                left = left.left
                x -= 1
            if right.right is not None:
                right = right.right
                x -= 1
            if left.left is None and right.right is None:
                x = 0
        up_left, down_left, up_right, down_right = left, left, right, right
        while y > 0:
            if up_left.up is not None:
                up_left = up_left.up
                y -= 1
                up_right = up_right.up
            if down_left.down is not None:
                down_left = down_left.down
                down_right = down_right.down
                y -= 1
            if up_left.up is None and down_left.down is None:
                y = 0
        self.corners = [up_left, up_right, down_left, down_right]

    def print(self):
        s = self.bag.print_pokemons() + '\n'
        i = ''
        for pokemon in self.inventory:
            i += '[' + str(pokemon) + '],'
        i = i[:-1] + '\n'
        return "{},{},{},{}".format(
            self.name, self.cash, self.stance,
            self.diff) + '\n' + s + i + self.bag.print_items()
Ejemplo n.º 30
0
def testAll():
    b = Bag()
    assert (b.size() == 0)
    assert (b.isEmpty())

    b.add(4)
    b.add(11)
    b.add(4)
    b.add(77)
    b.add(8)

    assert (b.size() == 5)
    assert (b.isEmpty() == False)

    assert (b.remove(44) == False)
    assert (b.remove(11))
    assert (b.size() == 4)
    assert (b.nrOccurrences(4) == 2)
    assert (b.search(77))
    assert (b.search(13) == False)

    itb = b.iterator()
    assert (itb.valid())
    cont = 0
    while (itb.valid()):
        cont += 1
        e = itb.getCurrent()
        itb.next()
        assert (b.search(e))
    assert (cont == b.size())
    itb.first()
    assert (itb.valid())
def testRemove():
    b = Bag()
    for i in range(-100,100):
        assert(b.remove(i) == False)

    assert(b.size() == 0)
    for i in range(-100,100, 2):
        b.add(i)

    for i in range (-100,100):
        if i % 2 == 0:
            assert(b.remove(i) == True)
        else :
            assert(b.remove(i) == False)

    assert(b.size() == 0)
    for i in range(-100,101, 2):
        b.add(i)
    for i in range(100,-100, -1):
        if i % 2 == 0:
            assert(b.remove(i) == True)
        else:
            assert(b.remove(i) == False)
    assert(b.size() == 1)
    b.remove(-100)
    for i in range(-100, 100):
        b.add(i)
        b.add(i)
        b.add(i)
        b.add(i)
        b.add(i)

    assert(b.size() == 1000)
    for i in range(-100,100):
        assert(b.nrOccurrences(i) == 5)

    for i in range(-100, 100):
        assert(b.remove(i) == True)

    assert(b.size() == 800)
    for i in range(-100, 100):
        assert(b.nrOccurrences(i) == 4)

    for i in range(-200, 200):
        if (i < -100) or (i >= 100):
            assert(b.remove(i) == False)
            assert(b.remove(i) == False)
            assert(b.remove(i) == False)
            assert(b.remove(i) == False)
            assert(b.remove(i) == False)
        else:
            assert(b.remove(i) == True)
            assert(b.remove(i) == True)
            assert(b.remove(i) == True)
            assert(b.remove(i) == True)
            assert(b.remove(i) == False)

    assert(b.size() == 0)
    for i in range(-1000,1000):
        assert(b.nrOccurrences(i) == 0)

    min = -200
    max = 200
    while min < max:
        b.add(min)
        b.add(max)
        min += 1
        max -= 1

    b.add(0)
    b.add(0)
    assert(b.size() == 402)
    for i in range(-30, 30):
        assert(b.search(i) == True)
        assert(b.remove(i) == True)
        if i != 0:
            assert(b.search(i) == False)
        else:
            assert(b.search(i) == True)

    assert(b.size() == 342)
Ejemplo n.º 32
0
#!/home/hmsjwzb/python/bin/python3

from Bag import Bag
from StdIn import StdIn
from math import sqrt

if __name__ == '__main__':
    In = StdIn()
    numbers = Bag()

    while not In.isEmpty():
        numbers.add(In.readDouble())

    N = numbers.size()
    sum = 0
    for x in numbers:
        sum += x

    mean = sum / N

    sum = 0.0
    for x in numbers:
        sum += (x - mean) * (x -mean)

    std = sqrt(sum / (N - 1))

    print("Mean: " + str(mean) + '\n')
    print("Std dev:" + str(std) + '\n')
Ejemplo n.º 33
0
from Student import Student
from Bag import Bag
yj = Student()
nikebag = Bag()
dg = Student()
adidas = Bag()
yj.bag = nikebag
dg.bag = adidas
yj.putItem(1, "laptop")
dg.putItem(1, "mouse")
nikebag.showItem(1)
adidas.showItem(1)