Beispiel #1
0
 def test_add(self):
     print('Checking for add')
     bag1 = Bag([random.randint(1,10) for i in range(1000)])
     bag2 = Bag()
     for el in iter(bag1):
         bag2.add(el)
     self.assertEqual(bag1,bag2, 'bag1 and bag 2 must be equal after adding all terms')
Beispiel #2
0
class Digraph():
    def __init__(self, V: int):
        self._V = V
        self._E = 0
        self._adj = Bag()
        for v in range(V):
            self._adj.add(Bag())

    @property
    def V(self):
        return self._V

    @property
    def E(self):
        return self._E

    def addEdge(self, v: int, w: int):
        self._adj[v].add(w)
        self._E += 1
        return self

    def adj(self, v) -> iter:
        return self._adj[v]

    def reverse(self):
        R = Digraph(self._V)
        for v in range(self._V):
            for w in self._adj:
                R.addEdge(w, v)
        return R
 def test_add(self):
     vals = [random.randint(1, 10) for i in range(1000)]
     bag1 = Bag(vals)
     random.shuffle(vals)
     bag2 = Bag()
     for item in vals:
         bag2.add(item)
     self.assertEqual(bag1, bag2, 'bags are not equal')
Beispiel #4
0
 def test_add(self):
     to_bag = [random.randrange(1, 11) for i in range(1000)]
     bag1 = Bag(to_bag)
     random.shuffle(to_bag)
     bag2 = Bag()
     for i in to_bag:
         bag2.add(i)
     self.assertEqual(bag1, bag2, "Bags are not equal.")
Beispiel #5
0
 def test_add(self):
     alist = [random.randint(1,10) for i in range(1000)]
     b1 = Bag(alist)
     random.shuffle(alist)
     b2 = Bag()
     for v in alist:
         b2.add(v)
     self.assertEqual(b1,b2)
 def test_add(self):
     temp_list = [random.randint(1,10) for i in range(1,1001)]
     b1 = Bag(temp_list)
     b2 = Bag()
     random.shuffle(temp_list)
     for i in temp_list:
         b2.add(i)
     self.assertEqual(b1,b2)
Beispiel #7
0
 def test_add(self):
     test = [random.randint(1, 10) for _ in range(1000)]
     bag1 = Bag(test)
     bag2 = Bag()
     random.shuffle(test)
     for v in test:
         bag2.add(v)
     self.assertEqual(bag1, bag2)
Beispiel #8
0
 def testadd(self):
     l = [random.randint(1, 10) for i in range(1000)]
     first = Bag(l)
     second = Bag([])
     random.shuffle(l)
     for i in l:
         second.add(i)
     assert first == second
Beispiel #9
0
def test_find():
    bag = Bag()
    bag.add(1, 10)
    bag.add(2, 20)
    bag.add(1, 10)
    bag.add(1, 20)
    assert bag.find(1) in bag.find_all(1)
    assert bag.find(2) == (2, 20)
    assert bag.find(10) == None
 def test_add(self):
     rand_list = [random.randint(1, 10)
                  for i in range(0, 1000)]  #Make 1000-value random list
     bag1 = Bag(rand_list)  #Create bag from random list
     bag2 = Bag()  #Create another bag from shuffled random list
     random.shuffle(rand_list)  #Shuffle random list
     for x in rand_list:
         bag2.add(x)
     self.assertEqual(bag1, bag2)
Beispiel #11
0
 def test_add(self):
     bag2 = []
     for i in range(0,1000):
         bag2.append((random.randint(1,10)))
     check_bag = Bag(bag2)
     check_bag2 = Bag()
     random.shuffle(bag2)
     for i in check_bag:
         check_bag2.add(i)
     self.assertEqual(check_bag,check_bag2)
Beispiel #12
0
 def testadd(self):
     rand_list = []
     for i in range(1000):
         rand_list.append(random.randint(1, 10))
     bag = Bag(rand_list)
     bag2 = Bag()
     random.shuffle(rand_list)
     for value in rand_list:
         bag2.add(value)
     assert bag == bag2
 def test_remove(self):
     vals = [random.randint(1, 10) for i in range(1000)]
     bag1 = Bag(vals)
     self.assertRaises(ValueError, lambda: bag1.remove(35))
     bag2 = Bag(vals)
     random.shuffle(vals)
     for item in vals:
         bag2.add(item)
     for item in vals:
         bag2.remove(item)
     self.assertEqual(bag1, bag2, 'bags are not equal')
Beispiel #14
0
 def test_remove(self):
     alist = [random.randint(1,10) for i in range(1000)]
     b1 = Bag(alist)
     self.assertRaises(ValueError,b1.remove,11)
     b2 = Bag(alist)
     random.shuffle(alist)
     for v in alist:
         b2.add(v)
     for v in alist:
         b2.remove(v)
     self.assertEqual(b1,b2)
 def test_remove(self):
     temp_list = []
     for i in range(1,1001):
         temp_list.append(random.randint(1,10))
     b1 = Bag(temp_list)
     self.assertRaises(ValueError,self.bag.remove,33)
     b2 = Bag(temp_list)
     for i in temp_list:
         b2.add(i)
         b2.remove(i)
     self.assertEqual(b1,b2)
Beispiel #16
0
def test_remove():
    bag = Bag()
    bag.add(1, 10)
    bag.add(2, 20)
    bag.add(1, 10)
    bag.add(1, 20)
    pairs = bag.find_all(1)
    assert bag.remove(1) in pairs
    assert len(bag.find_all(1)) == len(pairs) - 1
    assert bag.remove(2) == (2, 20)
    assert bag.remove(2) == None
Beispiel #17
0
 def test_add(self):
     alist = []
     for i in range(1000):
         alist.append(random.randint(1, 10))
     b1 = Bag(alist)
     random.shuffle(alist)
     b2 = Bag()
     for a in alist:
         b2.add(a)
     if b1 != b2:
         raise
Beispiel #18
0
def test_find_all():
    bag = Bag()
    bag.add(1, 10)
    bag.add(2, 20)
    bag.add(1, 10)
    bag.add(1, 20)
    pairs = bag.find_all(1)
    assert (1, 10) in pairs
    assert pairs.count((1, 10)) == 2
    assert bag.find_all(10) == []
    assert bag.find_all(2) == [(2, 20)]
Beispiel #19
0
 def testAdd(self):
     test_list = [random.randint(1,10) for i in range(1000)]
     test_bag1 = Bag(test_list)
     test_bag2 = Bag()
     
     random.shuffle(test_list)
     for i in test_list:
         test_bag2.add(i)
     
         
     
     self.assertTrue(test_bag1==test_bag2)
Beispiel #20
0
 def edges(self):
     l = Bag()
     for v in range(self._v):
         self_loops = 0
         for edge in self.adjacent(v):
             if edge.other(v) > v:
                 l.add(edge)
             elif edge.other(v) == v:
                 if self_loops % 2 == 0:
                     l.add(edge)
                 self_loops += 1
     return l
Beispiel #21
0
 def test_remove(self):
     to_bag = [random.randrange(1, 11) for i in range(1000)]
     bag1 = Bag(to_bag)
     self.assertRaises(ValueError, Bag.remove, bag1, 32)
     bag2 = Bag(to_bag)
     for i in to_bag:
         bag2.add(i)
     for i in to_bag:
         bag2.remove(i)
     self.assertEqual(bag1, bag2, "Bags are not equal.")
     
     
Beispiel #22
0
 def test_remove(self):
     print('Checking for remove')
     alist = [random.randint(1,10) for i in range(1000)]
     bag1 = Bag(alist)
     self.assertRaises(ValueError, Bag.remove,bag1,32)
     bag2 = Bag(alist)
     
     for el in alist:
         bag2.add(el)
     for el in alist:
         bag2.remove(el)
     
     self.assertEqual(bag1,bag2, 'Two bag must be same after removing elements from bag2')
Beispiel #23
0
    def test_remove(self):
        test = [random.randint(1, 10) for _ in range(1000)]
        bag1 = Bag(test)
        self.assertRaises(ValueError, bag1.remove, 86)

        bag2 = Bag(test)
        random.shuffle(test)
        test1 = [random.randint(1, 10) for _ in range(1000)]
        for v in test1:
            bag2.add(v)
        for v in test1:
            bag2.remove(v)
        self.assertEqual(bag1, bag2)
Beispiel #24
0
 def test_add(self):
     listone = []
     listtwo = []
     for x in range(1000):
         c = random.randint(1, 10)
         listone.append(c)
         listtwo.append(c)
     random.shuffle(listone)
     b1 = Bag(listone)
     b2 = Bag()
     for item in listtwo:
         b2.add(item)
     self.assertTrue(b1 == b2)
Beispiel #25
0
 def testRemove(self):
     
     test_list = [random.randint(1,10) for i in range(1000)]
     test_bag1 = Bag(test_list)
     
     self.assertRaises(ValueError,test_bag1.remove, 21)
     
     test_bag2 = Bag(test_list)
     for i in test_list:
         test_bag2.add(i)
     for i in test_list:
         test_bag2.remove(i)
     
     self.assertEqual(test_bag1,test_bag2)
Beispiel #26
0
 def testremove(self):
     l = [random.randint(1, 10) for i in range(1000)]
     first = Bag(l)
     try:
         first.remove(42)
     except Exception as e:
         assert type(e) == ValueError
         second = Bag(l)
         random.shuffle(l)
         for i in l:
             second.add(i)
         for i in l:
             second.remove(i)
         assert first == second
Beispiel #27
0
 def test_remove(self):
     alist = []
     for i in range(1000):
         alist.append(random.randint(1, 10))
     b1 = Bag(alist)
     self.assertRaises(ValueError, b1.remove, 11)
     b2 = Bag(alist)
     random.shuffle(alist)
     for v in alist:
         b2.add(v)
     for v in alist:
         b2.remove(v)
     if b1 != b2:
         raise
    def test_remove(self):
        rand_list = [random.randint(1, 10)
                     for i in range(0, 1000)]  #Make 1000-value random list
        bag1 = Bag(rand_list)  #Create bag from random list
        with self.assertRaises(ValueError):
            bag1.remove(43)

        bag2 = Bag(rand_list)
        random.shuffle(rand_list)  #Shuffle random list
        for x in rand_list:
            bag2.add(x)
        for x in rand_list:
            bag2.remove(x)
        self.assertEqual(bag1, bag2)
Beispiel #29
0
def main():
    born_before = Date(6, 1, 1988)
    print(born_before)
    bag = Bag()

    date = prompt_and_extract_date()
    while date is not None:
        bag.add(date)
        print(date)
        date = prompt_and_extract_date()

    print(len(bag))
    for date in bag:
        print(date)
        if date <= born_before:
            print("Should be atleast 21 years of age", date)
Beispiel #30
0
 def test_remove(self):
     listone = []
     listtwo = []
     for x in range(1000):
         c = random.randint(1, 10)
         listone.append(c)
         listtwo.append(c)
     random.shuffle(listtwo)
     b1 = Bag(listone)
     b2 = Bag(listone)
     self.assertRaises(ValueError, b1.remove, 53)
     for item in listtwo:
         b2.add(item)
     for item in listtwo:
         b2.remove(item)
     self.assertTrue(b1 == b2)
Beispiel #31
0
 def test_remove(self):
     bag2 = []
     for i in range(0,1000):
         bag2.append((random.randint(1,10)))
     check_bag = Bag(bag2)
     self.assertRaises(ValueError, check_bag.remove,21)
     check_bag2 = Bag(bag2)
     for i in bag2:
         check_bag2.add(i)
     for i in bag2:
         check_bag2.remove(i)
     self.assertEqual(check_bag,check_bag2)
     
     
     
         
                     
                      
     
Beispiel #32
0
 def testremove(self):
     rand_list = []
     for i in range(1000):
         rand_list.append(random.randint(1, 10))
     bag = Bag(rand_list)
     try:
         bag.remove(62)
     except ValueError:
         pass
     bag2 = Bag(rand_list)
     random.shuffle(rand_list)
     for value in rand_list:
         bag2.add(value)
     for value in rand_list:
         bag2.remove(value)
     assert bag == bag2
     
     
     
def main():
    import sys
    from bag import Bag
    from digraph import Digraph

    file_name = sys.argv[1]
    g = Digraph.from_txt(file_name)

    sources = Bag()
    for argument in sys.argv[2:]:
        s = int(argument)
        sources.add(s)

    dfs = DirectedDFS(g, sources)

    reachable = []
    for v in range(g.V()):
        if dfs.marked(v):
            reachable.append(str(v))

    print(" ".join(reachable))
Beispiel #34
0
class Trainer:
    '''Pokemon Trainer'''
    def __init__(self, name: str, *pokemons: tuple, level: int = 5):
        self.name = name.capitalize()
        self.bag = Bag()
        self.party = Party(
            *(Pokemon(pokemon,
                      level=randint(floor(level * 0.9), floor(level * 1.1)))
              for pokemon in pokemons) if pokemons else Pokemon(choice(
                  ['bulbasaur', 'charmander', 'squirtle', 'pikachu']),
                                                                level=5))
        self.in_battle = False

    def __str__(self):
        return f'<{self.__class__.__name__} {self.name}>'

    def __repr__(self):
        return f'<class {self.__class__.__name__}({self.name!r}, {", ".join([repr(name) for name in self.party.names])})>'

    def battle(self, other):
        def catch(self, pokemon):
            pass

        def throw_pokeball(self, pokeball):
            pass

    def teach(self, machine: object, pokemon_name: str) -> None:
        pokemon = self.party[pokemon_name]
        pokemon.learn(self.bag.use(machine))

    def give(self, item: object, pokemon_name: str) -> None:
        pokemon = self.party[pokemon_name]
        pokemon.held_item = self.bag.use(item)

    def use_item(self, item: object, pokemon_name: str) -> None:
        pokemon = self.party[pokemon_name]
        pokemon.use(self.bag.use(item))

    def pickup(self, item: object) -> None:
        self.bag.add(item)
Beispiel #35
0
    def test(self, args):
        numbers = Bag()

        while args:
            item = args.pop(0)
            assert isinstance(item, float) or isinstance(item, int)

            numbers.add(item)
        n = numbers.size()

        sum = 0
        for number in numbers:
            sum += number
        mean = sum / n

        sum = 0
        for number in numbers:
            sum += (number - mean)**2
        std = math.sqrt(sum / (n - 1))

        print("Mean: {0:.2f}".format(mean))
        print("Std dev: {0:.2f}".format(std))
Beispiel #36
0
def test_size():
    bag = Bag()
    assert bag.size() == 0
    bag.add(1, 10)
    assert bag.size() == 1
    bag.add(2, 20)
    assert bag.size() == 2
    bag.add(2, 20)
    assert bag.size() == 3
    bag.remove(10)
    assert bag.size() == 3
    bag.remove(1)
    assert bag.size() == 2
Beispiel #37
0
def test_keys():
    bag = Bag()
    assert bag.keys() == []
    bag.add(1, 10)
    assert bag.keys() == [1]
    bag.add(2, 20)
    assert sorted(bag.keys()) == [1, 2]
    bag.add(1, 10)
    assert sorted(bag.keys()) == [1, 2]
    bag.remove(1)
    assert sorted(bag.keys()) == [1, 2]
    bag.remove(2)
    assert bag.keys() == [1]
Beispiel #38
0
 def edges(self):
     l = Bag()
     for v in range(self._v):
         for edge in self.adjacent(v):
             l.add(edge)
     return l
Beispiel #39
0
from item import Item
from bag import Bag
from operator import attrgetter

items = [Item(150,20,1), Item(325,40,2), Item(600,50,3), Item(805,36,4), Item(430,25,5), Item(1200,64,6), Item(770,54,7), Item(60,18,8), Item(930,46,9), Item(353,28,10)]

b = Bag()
while True:
	nxt = items.pop(items.index(max(items, key=attrgetter('_coef'))))
	if b.getSize() + nxt.getVolume() <= 4200:
		b.add(nxt)
	else:
		break
print(b)


Beispiel #40
0
class Game:
    HUMAN = 'human'
    AI = 'ai'

    def __init__(self, root):
        self.__root = root
        self.__board = Board(root)
        self.__bag = Bag()
        self.__human = Human(root)
        self.__ai = Ai(root, self.__board, self.__bag)
        self.__turn = 1
        self.__player = self.__human
        self.__human_score = StringVar()
        self.__ai_score = StringVar()

    def __next_turn(self):
        self.__turn += 1
        self.__player = self.__human if self.__turn % 2 == 1 else self.__ai

    def main(self):
        print 'in main'
        width = self.__root.winfo_screenwidth() / 3.0
        height = 3 * self.__root.winfo_screenheight() / 4.0

        Game.pick_tiles(self.__human, self.__bag)
        Game.pick_tiles(self.__ai, self.__bag)

        self.__board.draw()
        self.__human.draw_rack()
        self.draw_game_buttons()

        self.__human_score.set(str(self.__human.get_points()))
        self.__ai_score.set(str(self.__ai.get_points()))

        self.__root.title('Scrabbletron')
        self.__root.geometry("%dx%d%+d%+d" % (width, height, 0, 0))
        self.__root.config(bg="#2F4F4F")

        self.__root.bind('<Button-1>', self.perform_placement)
        self.play()
        # self.__root.after(0, self.play)
        # self.__root.mainloop()

    def play(self):
        while self.__root:
            self.__root.update_idletasks()
            self.__root.update()

            if self.__turn % 2 == 0:
                start_time = time.time()
                anchors = self.__ai.get_anchor_squares()
                placements = self.__ai.calculate_cross_checks(anchors)
                possible_words = self.__ai.permute_rack_tiles(placements)
                print "len of possible moves: " + str(len(possible_words))
                valid_words = set()
                score_map = {}

                for board, placed, tile_dict in possible_words:
                    for word in self.__board.check_if_valid_word(
                        (board, placed), tile_dict):
                        valid_words.add(word)

                print self.__ai
                print 'len of valid moves: ' + str(len(valid_words))
                print valid_words
                print str(time.time() - start_time)
                # 	if self.__board.check_if_valid_word((board,placed),tile_dict):
                # 		valid_words.append(word)
                # print valid_words

                # for word in valid_words:
                # 	score_map[word] = self.__board.score_words(word,True)
                # print score_map
                self.__next_turn()
        # while not self.__bag.is_empty():
        # 	if self.__turn % 2 == 0:
        # 		self.__ai.get_anchor_squares()

        # while self.__human.get_rack_size() > 0 and self.__ai.get_rack_size() > 0:
        # 	pass

        # if self.__human.get_points() > self.__ai.get_points():
        # 	print 'You won!'
        # else:
        # 	print 'Sorry, Scrabbletron won :('
        # self.__root.after(0, self.play)

    def pass_turn(self):
        # remove any placed tiles and put on racks\
        self.__root.update()
        self.__next_turn()

    @staticmethod
    def pick_tiles(player, bag, allow_label=False):
        while not bag.is_empty():
            if not player.add_to_rack(bag.draw(), allow_label):
                break

    def exchange_letter(self):
        self.__root.update()
        tile = self.__player.get_selected_tile()
        # remove any placed tiles and put on rack
        if not tile and self.__turn % 2 == 1:
            alert_window = Toplevel(self.__root, height=500, width=500)
            alert = Label(alert_window,
                          text='You must select a tile to exchange.')
            alert.pack()
            close = Button(alert_window,
                           text="Close",
                           command=alert_window.destroy)
            close.pack()
        elif tile:
            if self.__bag.size() >= 7:
                self.__player.remove_from_rack(tile)
                self.__bag.add(tile)
                Game.pick_tiles(self.__player, self.__bag,
                                self.__turn % 2 == 1)
                self.__next_turn()

    def play_word(self):
        if len(self.__board.get_placed_tiles()) != 0:
            possible_word_points = self.__board.check_and_get_valid_placement(
                self.__turn)
            if possible_word_points:
                for group in possible_word_points:
                    if not self.__board.check_if_valid_word(group):
                        print 'not a word'
                        # put tiles back on rack
                        return
                self.__board.reconcile_settled_tiles()
                word_score = self.__board.score_words(possible_word_points)
                self.__human_score.set(str(
                    self.__human.add_points(word_score)))
                Game.pick_tiles(self.__human, self.__bag, True)
                self.__next_turn()
            else:
                #put tiles back on rack
                print 'invalid placing'
            self.__root.update_idletasks()

    # for human --> consider moving to human.py
    def perform_placement(self, event):
        if self.__turn % 2 == 1:
            rack_tile = self.__human.get_selected_tile()
            row, col = Board.get_coordinates(event)
            board_tile = self.__board.get_placed_tile(row, col)
            if not (row, col) == (-1, -1):
                if rack_tile and not board_tile:
                    self.__human.remove_from_rack(rack_tile)
                    self.__board.add_placed_tile(row, col, rack_tile)
                elif not rack_tile and board_tile:
                    removed_tile = self.__board.remove_placed_tile(row, col)
                    removed_tile.toggle()
                    self.__human.add_to_rack(board_tile, True)
                elif rack_tile and board_tile:
                    print self.__human.get_selected_tile()
            self.__root.update_idletasks()

    def draw_game_buttons(self):
        control_frame = Frame(self.__root)

        score_frame = Frame(control_frame)
        human_score_label = Label(score_frame,
                                  text="Your score: ").pack(side=LEFT, padx=2)
        human_score = Label(score_frame,
                            textvariable=self.__human_score).pack(side=LEFT)
        ai_score_label = Label(score_frame,
                               text="Scrabbletron's score: ").pack(side=LEFT,
                                                                   padx=2)
        ai_score = Label(score_frame,
                         textvariable=self.__ai_score).pack(side=LEFT)

        button_frame = Frame(control_frame)
        play_button = Button(button_frame,
                             text='Play word',
                             command=self.play_word).pack(side=TOP, pady=5)
        exchange_button = Button(button_frame,
                                 text="Exchange tile",
                                 command=self.exchange_letter).pack(side=TOP,
                                                                    pady=5)
        pass_button = Button(button_frame, text="Pass",
                             command=self.pass_turn).pack(side=TOP, pady=5)

        state_frame = Frame(button_frame)
        instruction_button = Button(state_frame,
                                    text="Instructions",
                                    command=self.display_instructions).pack(
                                        side=LEFT, padx=10)
        exit_button = Button(state_frame, text="Exit",
                             command=self.exit).pack(side=LEFT)

        score_frame.pack(side=TOP, pady=15)
        state_frame.pack(side=TOP)
        button_frame.pack(side=TOP)
        control_frame.pack(side=TOP)

    def display_instructions(self):
        text = """How to play against Scrabbletron:

	    You get a rack of 7 tiles to start the game. You must play words with these
	    7 tiles so that each word formed vertically and horizontally is a word. Whenever 
	    you play a word, make sure that it touches at least one other letter on the board 
	    (not diagonally.) The first move must touch the star in the middle of the board.
	    
	    To play a tile, click and drag the tile to the board. When you play a tile, make 
	    sure that it snaps into a space. If it doesn't, then it didn't place and you have 
	    to do it again.

	    " " tiles are blank tiles. They can be played as any letter.

	    If you can't find any words to make, you can exchange. Exchanging 
	    You get a certain amount of points based on the letters you played.
	    Special Score Tiles:
	    \tTWS (triple word score): Multiplies your score for that turn by 3.
	    \tDWS (double word score): Multiplies your score for that turn by 2.
	    \tTLS (triple letter score): Multiplies your score for that letter by 3.
	    \tDLS (double letter score): Multiplies your score for that letter by 2.
	    
	    Once you play a word, you draw tiles until you have seven again.
	    The game ends when there are no tiles left in the bag."""

        instructions_window = Toplevel(self.__root, height=800, width=700)
        instructions_window.title("Instructions")
        instructions_label = Label(instructions_window,
                                   text=text,
                                   justify=LEFT)
        instructions_label.place(height=750, width=650)
        close_button = Button(instructions_label,
                              text="Close",
                              command=instructions_window.destroy)
        close_button.place(x=325, y=600)

    def exit(self):
        self.__root.update()
        self.__root.destroy()
        print("Thanks for playing!\n\t-Chaz & Isaiah")
        sys.exit(0)
Beispiel #41
0
class TestBag(unittest.TestCase):

    def setUp(self):
        self.bag = Bag()

    def test_is_empty(self):
        self.assertTrue(self.bag.is_empty())
        self.bag.add(3)
        self.assertTrue(not self.bag.is_empty())

    def test_size(self):
        self.assertEqual(self.bag.size(), 0)
        self.bag.add(3)
        self.assertEqual(self.bag.size(), 1)

    def test_add(self):
        self.bag.add(3)
        self.assertEqual(self.bag._a, [3])  # This code smells.

    def test_each(self):
        self.bag.add(3)
        self.bag.add('foo')
        self.bag.add([])
        lst = []
        self.bag.each(lambda x: lst.append(x))
        self.assertEqual([3, 'foo', []], lst)