Beispiel #1
0
 def test_equal(self):
     to_bag = [random.randrange(1, 11) for i in range(1000)]
     bag1 = Bag(to_bag)
     bag2 = Bag(to_bag)
     self.assertEqual(bag1, bag2, "Bags are not equal.")
     bag1.remove(to_bag[0])
     self.assertNotEqual(bag1, bag2, "Bags should not be equal.")
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
Beispiel #3
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 #4
0
def deliver(instructions,
            meta_requests,
            db_connection_info=MongoConnectionInfo()):
    """deliver artifacts defined by each of meta_requests then apply unbox instructions to each."""
    created_files = []
    connected_bag = Bag(db_connection_info)

    if isinstance(meta_requests, dict):
        print('metarequest is a dict, let make a list!')
        meta_requests = [meta_requests]

    direct_requirements = [dependencies.Requirement(r) for r in meta_requests]
    meta_request = [dr.meta_request() for dr in direct_requirements]
    meta_requests, gr = connected_bag.requirements_discover(
        direct_requirements)
    print('results from bag: ' + str(meta_requests) + '   ' + str(gr))

    if isinstance(meta_requests, list):
        for r in meta_requests:
            print("REQUIRE> " + str(r))
            created_files += deliver_one(instructions,
                                         r,
                                         db_connection_info=db_connection_info)
    else:
        print("REQUIRE FAILS> " + str(meta_requests))

    return [s.replace('\\', '/') for s in created_files], gr
Beispiel #5
0
 def __init__(self):
     pygame.init()
     # Control how held keys are repeated
     pygame.key.set_repeat(100, 100)
     resolution = (799, 705)
     # The window can be resized
     self.window = pygame.display.set_mode(resolution, pygame.RESIZABLE)
     # Window title
     pygame.display.set_caption("MacGyver")
     self.images = {
         "floor_image":
         pygame.image.load("media/floor.png").convert_alpha(),
         "wall_image":
         pygame.image.load("media/wall.png").convert_alpha(),
         "tube_image":
         pygame.image.load("media/tube.png").convert_alpha(),
         "seringue_image":
         pygame.image.load("media/seringue.png").convert_alpha(),
         "needle_image":
         pygame.image.load("media/needle.png").convert_alpha(),
         "guardian_image":
         pygame.image.load("media/guardian.png").convert_alpha(),
         "ether_image":
         pygame.image.load("media/ether.png").convert_alpha(),
         "mac_image":
         pygame.image.load("media/mac.png").convert_alpha()
     }
     self.font = pygame.font.SysFont("herculanum", 35)
     self.bag = Bag()
     self.restart()
     self.run()
Beispiel #6
0
 def test_this_and_that(self):
     self.assert_(2 == len(self.fake_dict.keys()))
     cat_hits = self.fake_dict[Bag("cat")]
     self.assert_(2 == len(cat_hits))
     self.assert_(cat_hits == set(["cat", "tac"]))
     self.assert_(1 == len(self.fake_dict[Bag("fred")]))
     self.assert_(self.fake_dict[Bag("fred")] == set(["fred"]))
Beispiel #7
0
def info_cmd(argv):
    parser = optparse.OptionParser(usage='rosbag info [options] BAGFILE1 [BAGFILE2 BAGFILE3 ...]',
                                   description='Summarize the contents of one or more bag files.')
    parser.add_option('-y', '--yaml', dest='yaml', default=False, action='store_true', help='print information in YAML format')
    parser.add_option('-k', '--key',  dest='key',  default=None,  action='store',      help='print information on the given key')
    parser.add_option(      '--freq', dest='freq', default=False, action='store_true', help='display topic message frequency statistics')
    (options, args) = parser.parse_args(argv)

    if len(args) == 0:
        parser.error('You must specify at least 1 bag file.')
    if options.key and not options.yaml:
        parser.error('You can only specify key when printing in YAML format.')

    for i, arg in enumerate(args):
        try:
            b = Bag(arg, 'r', skip_index=not options.freq)
            if options.yaml:
                info = b._get_yaml_info(key=options.key)
                if info is not None:
                    print info
            else:
                print b
            b.close()
            if i < len(args) - 1:
                print '---'
        
        except ROSBagUnindexedException, ex:
            print >> sys.stderr, 'ERROR bag unindexed: %s.  Run rosbag reindex.' % arg
        except ROSBagException, ex:
            print >> sys.stderr, 'ERROR reading %s: %s' % (arg, str(ex))
Beispiel #8
0
def info_cmd(argv):
    parser = optparse.OptionParser(usage='rosbag info [options] BAGFILE1 [BAGFILE2 BAGFILE3 ...]',
                                   description='Summarize the contents of one or more bag files.')
    parser.add_option('-y', '--yaml', dest='yaml', default=False, action='store_true', help='print information in YAML format')
    parser.add_option('-k', '--key',  dest='key',  default=None,  action='store',      help='print information on the given key')
    parser.add_option(      '--freq', dest='freq', default=False, action='store_true', help='display topic message frequency statistics')
    (options, args) = parser.parse_args(argv)

    if len(args) == 0:
        parser.error('You must specify at least 1 bag file.')
    if options.key and not options.yaml:
        parser.error('You can only specify key when printing in YAML format.')

    for i, arg in enumerate(args):
        try:
            b = Bag(arg, 'r', skip_index=not options.freq)
            if options.yaml:
                info = b._get_yaml_info(key=options.key)
                if info is not None:
                    print info
            else:
                print b
            b.close()
            if i < len(args) - 1:
                print '---'
        
        except ROSBagUnindexedException, ex:
            print >> sys.stderr, 'ERROR bag unindexed: %s.  Run rosbag reindex.' % arg
        except ROSBagException, ex:
            print >> sys.stderr, 'ERROR reading %s: %s' % (arg, str(ex))
Beispiel #9
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):
     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 #11
0
 def test_equal(self):
     test = [random.randint(1, 10) for _ in range(1000)]
     bag1 = Bag(test)
     random.shuffle(test)
     bag2 = Bag(test)
     self.assertEqual(bag1, bag2)
     bag1.remove(test[0])
     self.assertNotEqual(bag1, bag2)
Beispiel #12
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 #13
0
 def test__eq__(self):
     l = [random.randint(1, 10) for i in range(1000)]
     first = Bag(l)
     random.shuffle(l)
     second = Bag(l)
     assert first == second
     first.remove(l[0])
     assert first != second
Beispiel #14
0
def deliver_one(instructions,
                meta_request,
                db_connection_info=MongoConnectionInfo()):

    connected_bag = Bag(db_connection_info)
    package = connected_bag.take(meta_request)
    package_content = io.BytesIO(package)
    return gz_unbox(unbox_instructions=instructions, mem=package_content)
Beispiel #15
0
 def test_equals(self):
     alist = [random.randint(1,10) for i in range(1000)]
     b1 = Bag(alist)
     random.shuffle(alist)
     b2 = Bag(alist)
     self.assertEqual(b1,b2)
     b1.remove(alist[0])
     self.assertNotEquals(b1,b2)
Beispiel #16
0
def test_this_and_that(fake_dict):
    assert (2 == len(fake_dict.keys()))
    key = Bag("cat")
    cat_hits = sorted(fake_dict[key])
    assert (cat_hits == ["cat", "tac"])

    assert (1 == len(fake_dict[Bag("fred")]))
    assert (list(fake_dict[Bag("fred")])[0] == "fred")
Beispiel #17
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 #18
0
 def test_this_and_that(self):
     self.assert_(2 == len(self.fake_dict.keys()))
     cat_hits = self.fake_dict[Bag("cat")]
     self.assert_(2 == len(cat_hits))
     self.assert_(cat_hits[0] == "cat")
     self.assert_(cat_hits[1] == "tac")
     self.assert_(1 == len(self.fake_dict[Bag("fred")]))
     self.assert_(self.fake_dict[Bag("fred")][0] == "fred")
 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)
 def test_eq(self):
     temp_list = [random.randint(1,10) for i in range(1,1001)]
     b1 = Bag(temp_list)
     random.shuffle(temp_list)
     b2 = Bag(temp_list)
     self.assertEqual(b1,b2)
     b2.remove(temp_list[0])
     self.assertNotEqual(b1,b2)
 def test_equals(self):
     vals = [random.randint(1, 10) for i in range(1000)]
     bag1 = Bag(vals)
     random.shuffle(vals)
     bag2 = Bag(vals)
     self.assertTrue(bag1 == bag2, 'bags are not equal')
     bag1.remove(vals[0])
     self.assertFalse(bag1 == bag2, 'bags are not supposed to be equal')
Beispiel #22
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 #23
0
 def __init__(self):
     self.bag = Bag()
     self.bag.createTiles()
     self.bag.shuffleTiles()
     self.board = Board()
     self.player_list = []
     self.strategy_to_player = {}
     for strategy_num in range(1, 3):
          self.player_list.append(Player(strategy_num))
Beispiel #24
0
 def testEqual(self):
     test_list = [random.randint(1,10) for i in range(1000)]
     test_bag1 = Bag(test_list)
     random.shuffle(test_list)
     test_bag2 = Bag(test_list)
     
     self.assertTrue(test_bag1==test_bag2)
     test_bag2.remove(test_list[0])
     self.assertFalse(test_bag1==test_bag2)
 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 #26
0
 def test_equal(self):
     print('Checking for equal')
     alist = [random.randint(1,10) for i in range(1000)]
     bag1 = Bag(alist)
     random.shuffle(alist)
     bag2 = Bag(alist)
     self.assertEqual(bag1, bag2, 'Two back must be equal initially')
     bag2.remove(alist[0])
     self.assertNotEqual(bag1, bag2, 'Two back must not be equal after removing the first element of bag2')
Beispiel #27
0
    def __init__(self, *args):
        self.players = []
        for count, arg in enumerate(*args, start=1):
            if not arg:
                self.players.append(HumanPlayer(f'Player {count}'))
            else:
                self.players.append(Player(f'Computer {count}'))

        self.game_bag = Bag()
        self.round = 1
Beispiel #28
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 #29
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
Beispiel #30
0
 def testequals(self):
     rand_list = []
     for i in range(1000):
         rand_list.append(random.randint(1, 10))
     bag = Bag(rand_list)
     random.shuffle(rand_list)
     bag2 = Bag(rand_list)
     assert bag == bag2
     bag.remove(rand_list[0])
     assert bag != bag2
Beispiel #31
0
 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
Beispiel #32
0
 def __init__(self, PID_players=[], PID_my=[]):
     self.lock = threading.RLock()
     self.board = Board()    # Master Board
     self.scores = []        # List of all players' scores
     self.bag = Bag()        # Bag of remaining tiles
     # Used to check if first move overlaps with center tile
     self.first_move = True
     # List of PID of players so board can use imported send_message
     self.PID_players = PID_players
     self.PID_my = PID_my    # Current PID
Beispiel #33
0
 def test_eq(self):
     bag2 = []
     for i in range(0,1000):
         bag2.append((random.randint(1,10)))
     check_bag = Bag(bag2)
     random.shuffle(bag2)
     check_bag2 = Bag(bag2)
     self.assertEqual(check_bag,check_bag2)
     check_bag.remove(bag2[0])
     self.assertNotEqual(check_bag,check_bag2)
Beispiel #34
0
def decode_rule(rule):
    idx = rule.index(BAGS_CONTAINED)
    color = rule[0:idx].strip()
    b = Bag(color)
    if rule.endswith('no other bags.') == False:
        contains = rule[idx + len(BAGS_CONTAINED):].strip().split(',')
        for contain in contains:
            c, n = decode_sub_colors(contain.strip())
            b.add_contained_bag(c, n)
    return b
Beispiel #35
0
 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()
Beispiel #36
0
def evaluate_pathway(list_of_paths):
    scores = []

    # create a set of all participating enzymes, and count the number of enzymes that are not trivial
    total_path_length = 0
    enzyme_bag = Bag()
    enzyme_type_bag = Bag()
    for path in list_of_paths:
        for enzyme in path_to_enzyme_list(path):
            if (not enzyme in pp_enzymes):
                total_path_length += 1
                enzyme_bag[enzyme] += 1
                enzyme_type_bag[enzyme_types[enzyme]] += 1
    scores.append((params['TL'], total_path_length))
    scores.append((params['NE'], enzyme_type_bag['EPI']))
    scores.append((params['NI'], enzyme_type_bag['ISO']))
    scores.append((params['NK'], enzyme_type_bag['KIN']))
    scores.append((params['ND'], enzyme_type_bag['DHG']))

    num_isoenzymes = 0
    for (enzyme, count) in enzyme_bag.itercounts():
        if (count > 1):
            num_isoenzymes += 1
    scores.append((params['MIE'], num_isoenzymes))

    total_phosphorilation_distance = 0
    for path in list_of_paths:
        for enzyme in path_to_enzyme_list(path):
            if (enzyme_types[enzyme] == "KIN"):
                break
            else:
                total_phosphorilation_distance += 1
    scores.append((params['TPD'], total_phosphorilation_distance))

    # NTE - Number maximum number of same-product epimerases
    G = pathway_to_graph(list_of_paths)
    max_epimerase_count = 0
    max_split = 0
    for v in G.itervertices():
        epimerase_count = 0
        for child in G[v]:
            if (enzyme_types[(v, child)] == "EPI"):
                epimerase_count += 1
        max_epimerase_count = max(max_epimerase_count, epimerase_count)
        max_split = max(max_split, len(G[v]))
    scores.append((params['NTE'], max_epimerase_count))

    # copy on the scores that have a parameter which is not None.
    chosen_scores = []
    for (p, s) in scores:
        if (p != None):
            chosen_scores.append((p, s))
    chosen_scores.sort()
    return tuple([s[1] for s in chosen_scores])
Beispiel #37
0
 def test_equals(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(listtwo)
     self.assertTrue(b1 == b2)
Beispiel #38
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
 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 #40
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 evaluate_pathway(list_of_paths):
    scores = []

    # create a set of all participating enzymes, and count the number of enzymes that are not trivial
    total_path_length = 0
    enzyme_bag = Bag()
    enzyme_type_bag = Bag()
    for path in list_of_paths:
        for enzyme in path_to_enzyme_list(path):
            if (not enzyme in pp_enzymes):
                total_path_length += 1
                enzyme_bag[enzyme] += 1
                enzyme_type_bag[enzyme_types[enzyme]] += 1
    scores.append((params['TL'], total_path_length))
    scores.append((params['NE'], enzyme_type_bag['EPI']))
    scores.append((params['NI'], enzyme_type_bag['ISO']))
    scores.append((params['NK'], enzyme_type_bag['KIN']))
    scores.append((params['ND'], enzyme_type_bag['DHG']))
    
    num_isoenzymes = 0
    for (enzyme, count) in enzyme_bag.itercounts():
        if (count > 1):
            num_isoenzymes += 1
    scores.append((params['MIE'], num_isoenzymes))
    
    total_phosphorilation_distance = 0
    for path in list_of_paths:
        for enzyme in path_to_enzyme_list(path):
            if (enzyme_types[enzyme] == "KIN"):
                break
            else:
                total_phosphorilation_distance += 1
    scores.append((params['TPD'], total_phosphorilation_distance))

    # NTE - Number maximum number of same-product epimerases
    G = pathway_to_graph(list_of_paths)
    max_epimerase_count = 0
    max_split = 0
    for v in G.itervertices():
        epimerase_count = 0
        for child in G[v]:
            if (enzyme_types[(v, child)] == "EPI"):
                epimerase_count += 1    
        max_epimerase_count = max(max_epimerase_count, epimerase_count)
        max_split = max(max_split, len(G[v]))
    scores.append((params['NTE'], max_epimerase_count))
    
    # copy on the scores that have a parameter which is not None.
    chosen_scores = []
    for (p, s) in scores:
        if (p != None):
            chosen_scores.append((p, s))
    chosen_scores.sort()
    return tuple([s[1] for s in chosen_scores])
Beispiel #42
0
    def __init__(self, *args):
        self.board = Board()
        self.bag = Bag()

        self.nextPiece = None

        self.onBoard = False

        self.highlight = 0

        self.isPlayerOne = True
Beispiel #43
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 #44
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 #45
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 #46
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 #47
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 #48
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 #49
0
    def randomized_select(self, select_range, priority_fn, lowestPriority=False):
        solution = list()
        total_profit = 0
        bag = Bag(self.P, self.M, self.constraints)
        options = list()
        for item in self.items:
            options.append((item, priority_fn(item)))
        options.sort(key=lambda x: -x[1])
        if lowestPriority:
            options = list(reversed(options))
        options = [x[0] for x in options]

        while len(options) > 0 and not bag.full():
            items = options[:min(select_range, len(options))]
            item = items[int(random() * len(items))]
            options.remove(item)
            print(" progress: {0:.2f} %".format(max(bag._weight / bag.P, bag._cost/bag.M) * 100), end="\r")
            if bag.has_enough_weight_for(item.weight) and bag.has_enough_money_for(item.cost):
                bag.take(item)
                solution.append(item)
                total_profit += item.profit
                new_options = list()
                for x in options:
                    if bag.can_take(x.classNumber):
                        new_options.append(x)
                options = new_options
        return (total_profit, solution)
Beispiel #50
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 #51
0
def bag_op(inbag_filenames, allow_unindexed, copy_fn, op, output_dir=None, force=False, quiet=False):
    for inbag_filename in inbag_filenames:
        # Check we can read the file
        try:
            inbag = Bag(inbag_filename, 'r', allow_unindexed=allow_unindexed)
        except ROSBagUnindexedException:
            print >> sys.stderr, 'ERROR bag unindexed: %s.  Run rosbag reindex.' % inbag_filename
            continue
        except (ROSBagException, IOError), ex:
            print >> sys.stderr, 'ERROR reading %s: %s' % (inbag_filename, str(ex))
            continue

        # Determine whether we should copy the bag    
        copy = copy_fn(inbag)
        
        inbag.close()

        # Determine filename for output bag
        if output_dir is None:
            outbag_filename = inbag_filename
        else:
            outbag_filename = os.path.join(output_dir, os.path.split(inbag_filename)[1])

        backup_filename = None
        if outbag_filename == inbag_filename:
            # Rename the input bag to ###.orig.###, and open for reading
            backup_filename = '%s.orig%s' % os.path.splitext(inbag_filename)
            
            if not force and os.path.exists(backup_filename):
                if not quiet:
                    print >> sys.stderr, 'Skipping %s. Backup path %s already exists.' % (inbag_filename, backup_filename)
                continue
            
            try:
                if copy:
                    shutil.copy(inbag_filename, backup_filename)
                else:
                    os.rename(inbag_filename, backup_filename)
            except OSError, ex:
                print >> sys.stderr, 'ERROR %s %s to %s: %s' % ('copying' if copy else 'moving', inbag_filename, backup_filename, str(ex))
                continue
            
            source_filename = backup_filename
Beispiel #52
0
    def __init__(self, players, computers, dictionary='sowpods.txt'):
        """Sets up initial game state with player names given"""

        self.bag = Bag()
        self.board = Board()
        self.player_order = players + sorted(computers.keys())
        self.computers = computers
        self.players = {}
        for player in players:           
            self.players[player] = Player(player,self)
        for computer in computers:
            self.players[computer] = AI(computer, self, computers[computer])
        self.turn = 0
        self.played = False
        self.dictionary = Dictionary(dictionary)
Beispiel #53
0
 def greedy_on_fn(self, priority_fn, lowestPriority=False):
     solution = list()
     total_profit = 0
     bag = Bag(self.P, self.M, self.constraints)
     queue = get_priority_queue(self.items, priority_fn, lowestPriority)
     
     while not queue.isEmpty() and not bag.full():
         item = queue.pop()
         #print(" remaining items: {0:.2f}%".format(queue.count / self.N * 100), end="\r")
         print(" progress: {0:.2f} %".format(max(bag._weight / bag.P, bag._cost/bag.M) * 100), end="\r")
         if bag.has_enough_weight_for(item.weight) and bag.has_enough_money_for(item.cost):
             if bag.can_take(item.classNumber):
                 solution.append(item)
                 bag.take(item)
                 total_profit += item.profit
     return (total_profit, solution)
Beispiel #54
0
 def edges(self):
     l = Bag()
     for v in range(self._v):
         for edge in self.adjacent(v):
             l.add(edge)
     return l
Beispiel #55
0
from item import Item
from bag import Bag

def makeBag(pattern, dic):
	aux = []
	for x in range(0 , len(pattern)):
		if pattern[x] == 1:
			aux.append(dic[x])
	return Bag(aux)
	


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)]

bb = Bag()

for a in range(0, 2):
	for b in range(0, 2):
		for c in range(0, 2):
			for d in range(0, 2):
				for e in range(0, 2):
					for f in range(0, 2):
						for g in range(0, 2):
							for h in range(0, 2):
								for i in range(0, 2):
									for j in range(0, 2):
										pattern = [a,b,c,d,e,f,g,h,i,j]
										bag = makeBag(pattern, items)
										if bag.getSize() <= 4200:
											if bag.getTotalValue() >= bb.getTotalValue():
												bb = bag
Beispiel #56
0
    def run_algorithm(self, num_solution_before_stop=100000, time_out=1000000):
        """
        This is where we implement our logic and algorithms

        Useful Parameters:
        self.P -- max weight we can carry
        self.M -- max purchasing power in dollars
        self.N -- total number of avaliable items
        self.C -- total number of constraints
        self.items -- all items avaliable for choice
        self.constraints -- a Constraint class with constraints
        """

        # STEP: Create a hashmap from class number to its items
        item_map = dict()
        for item in self.items:
            if item.classNumber not in item_map:
                item_map[item.classNumber] = set()
            item_map[item.classNumber].add(item)

        # STEP: Calculate the total weight, cost, value, and profit of each class
        def get_class_stats(items):
            total_weight = 0
            total_cost = 0
            total_value = 0
            total_profit = 0
            for item in items:
                total_weight += item.weight
                total_cost += item.cost
                total_value += item.value
                total_profit += item.profit
            return (total_weight, total_cost, total_value, total_profit)

        class_stats = dict() # Format: key: class -> value: (weight, cost, value, profit)
        for classNumber in item_map.keys():
            class_stats[classNumber] = get_class_stats(item_map[classNumber])

        # STEP: Create a BAG instance
        bag = Bag(self.P, self.M, self.constraints)

        # STEP: PriorityQueues of class's values

        fn_extract_profit_per_weight_ratio = lambda x: x.profit_per_weight_ratio()
        
        def fn_extractclass_ratio(x):
            weight, _, _, profit = class_stats[x]
            if weight == 0:
                ratio = float("inf")
            else:
                ratio = profit / weight
            return ratio


        class_queue = PriorityQueue(lowest_priority=False) # based on class's item profit_per_weight_ratio
        for classNumber in item_map.keys():
            class_queue.push(classNumber, fn_extractclass_ratio(classNumber))

        def add_to_queue(items, fn_extract_priority, queue):
            for item in items:
                priority_value = fn_extract_priority(item)
                queue.push(item, -priority_value)
            return queue

        def get_queue_of_items(items, fn_extract_priority):
            queue = PriorityQueue(lowest_priority=False)
            return add_to_queue(items, fn_extract_priority, queue)


        # STEP: pick from the bag with highest ratio
        solutions_found = dict()
        num_solution_found = 0
        iteration = 0

        class_not_used_due_to_conflict = Queue()

        add_back_conflicts = True

        while num_solution_found <= num_solution_before_stop and iteration <= time_out:
            while not class_queue.isEmpty() and iteration <= time_out:
                iteration += 1
                if iteration % (time_out / 1000) == 0:
                    print("iteration {0} -- rate: {1:.2f} %".format(iteration, iteration / time_out * 100), end="\r")
                if not class_not_used_due_to_conflict.isEmpty():
                    class_to_use  = class_not_used_due_to_conflict.pop()
                    add_back_conflicts = not add_back_conflicts
                else: 
                    class_to_use = class_queue.pop()
                    add_back_conflicts = not add_back_conflicts
                if bag.can_take(class_to_use):
                    items_queue = get_queue_of_items(item_map[class_to_use], \
                                                fn_extract_profit_per_weight_ratio)
                    item = items_queue.pop()
                    while bag.take(item):
                        if not items_queue.isEmpty():
                            item = items_queue.pop()
                        else:
                            break
                    num_solution_found += 1
                    solutions_found[bag.score()] =  bag.items()
                    print("solution {0} found".format(num_solution_found))
                else:
                    class_not_used_due_to_conflict.push(class_to_use)
                if num_solution_found >= num_solution_before_stop:
                    break
            # print("iteration {0}".format(iteration))
            iteration += 1
            if add_back_conflicts:
                add_to_queue(class_not_used_due_to_conflict.list, fn_extractclass_ratio, class_queue)
            if num_solution_found >= num_solution_before_stop:
                break

        # STEP: return the best combination found
        bestSolution = []
        bestProfit = 0
        for profit, soln in solutions_found.items():
            if profit > bestProfit:
                bestProfit = profit
                bestSolution = soln
        return bestSolution
Beispiel #57
0
                else:
                    os.rename(inbag_filename, backup_filename)
            except OSError, ex:
                print >> sys.stderr, 'ERROR %s %s to %s: %s' % ('copying' if copy else 'moving', inbag_filename, backup_filename, str(ex))
                continue
            
            source_filename = backup_filename
        else:
            if copy:
                shutil.copy(inbag_filename, outbag_filename)
                source_filename = outbag_filename
            else:
                source_filename = inbag_filename

        try:
            inbag = Bag(source_filename, 'r', allow_unindexed=allow_unindexed)

            # Open the output bag file for writing
            try:
                if copy:
                    outbag = Bag(outbag_filename, 'a', allow_unindexed=allow_unindexed)
                else:
                    outbag = Bag(outbag_filename, 'w')
            except (ROSBagException, IOError), ex:
                print >> sys.stderr, 'ERROR writing to %s: %s' % (outbag_filename, str(ex))
                inbag.close()
                continue

            # Perform the operation
            try:
                op(inbag, outbag, quiet=quiet)
Beispiel #58
0
                      action="store",
                      type="string",
                      dest="dict_fn",
                      default=dict.default_dict_name,
                      metavar="FILE",
                      help="location of word list")

    (options, args) = parser.parse_args()

    if 0 == len(args):
        parser.print_help()
        sys.exit(0)

    dict_hash_table = dict.snarf_dictionary(options.dict_fn)

    the_phrase = Bag(args[0])
    print("Pruning dictionary.  Before: {} bags ...".format(len(dict_hash_table.keys())),
          file=sys.stderr, end='')

    # Now convert the hash table to a list, longest entries first.  (This
    # isn't necessary, but it makes the more interesting anagrams appear
    # first.)

    # While we're at it, prune the list, too.  That _is_ necessary for the
    # program to finish before you grow old and die.

    the_dict_list = [[k, dict_hash_table[k]]
                     for k in dict_hash_table.keys()
                     if the_phrase.subtract(k)]

    # Note that sorting entries "alphabetically" only makes partial sense,