Ejemplo n.º 1
0
 def test_iterlen_empty(self):
     it = iter(blist())
     if hasattr(it, '__next__'):
         self.assertRaises(StopIteration, it.__next__)
     else:
         self.assertRaises(StopIteration, it.next)
     self.assertEqual(it.__length_hint__(), 0)
Ejemplo n.º 2
0
    def __init__(self,
                 n=None,
                 max_prime=9999999999971.,
                 ksize=None,
                 input_file_name=None,
                 save_kmers='n',
                 hash_list=None,
                 rev_comp=False):
        if n is None:
            raise Exception
        if ksize is None:
            raise Exception

        if ksize % 2 == 0:
            raise Exception(
                "Due to an issue with khmer, only odd ksizes are allowed")

        self.ksize = ksize
        self.hash_list = hash_list

        # get a prime to use for hashing
        p = get_prime_lt_x(max_prime)
        self.p = p

        # initialize sketch to size n
        #self._mins = [float("inf")]*n
        self._mins = blist([p] * n)

        # initialize the corresponding counts
        self._counts = blist([0] * n)

        # initialize the list of kmers used, if appropriate
        if save_kmers == 'y':
            self._kmers = blist([''] * n)
        else:
            self._kmers = None

        # Initialize file name (if appropriate)
        self.input_file_name = input_file_name
        if self.input_file_name:
            self.parse_file(rev_comp=rev_comp)

        # Optional container for the true number of k-mers in the genome used to populate the sketch
        self._true_num_kmers = 0
Ejemplo n.º 3
0
    def __init__(self, coords, dims, leaf):
        # Rectangle Data
        self.coords = coords
        self.dims = dims

        # Is this node leaf?
        self.leaf = leaf

        # Ref back to parent
        self.parent = None

        # Children list of the Node
        self.children = blist()
Ejemplo n.º 4
0
    def __init__(self, n=None, max_prime=9999999999971., ksize=None, input_file_name=None, save_kmers='n', hash_list=None,
                 rev_comp=False):
        if n is None:
            raise Exception
        if ksize is None:
            raise Exception

        if ksize % 2 == 0:
            raise Exception("Due to an issue with khmer, only odd ksizes are allowed")

        self.ksize = ksize
        self.hash_list = hash_list

        # get a prime to use for hashing
        p = get_prime_lt_x(max_prime)
        self.p = p

        # initialize sketch to size n
        #self._mins = [float("inf")]*n
        self._mins = blist([p]*n)

        # initialize the corresponding counts
        self._counts = blist([0]*n)

        # initialize the list of kmers used, if appropriate
        if save_kmers == 'y':
            self._kmers = blist(['']*n)
        else:
            self._kmers = None

        # Initialize file name (if appropriate)
        self.input_file_name = input_file_name
        if self.input_file_name:
            self.parse_file(rev_comp=rev_comp)

        # Optional container for the true number of k-mers in the genome used to populate the sketch
        self._true_num_kmers = 0
Ejemplo n.º 5
0
    def add(self, dlist):
        """
        Add a list of elements to our collection, keeping it in order.
        Don't add nan/inf values
        """

        to_add = blist(d for d in dlist if np.isfinite(d))

        if len(to_add) == 0:
            return
        if len(self.slist) == 0:
            self.slist = blist(sorted(to_add))
            return

        #cheap version (works better for large length arrays)
        # ie when we have grid*box >1e6
        # 2.13795 s for test image
        #self.slist=blist(merge(to_add,self.slist))

        #cheaper!
        #1.96215 s for test image
        self.slist.extend(to_add)
        self.slist.sort()
        return
Ejemplo n.º 6
0
    def pickle_tests(self, pickler):
        self.pickle_test(pickler, blist())
        self.pickle_test(pickler, blist(list(range(limit))))
        self.pickle_test(pickler, blist(list(range(limit+1))))
        self.pickle_test(pickler, blist(list(range(n))))

        x = blist([0])
        x *= n
        self.pickle_test(pickler, x)
        y = blist(x)
        y[5] = 'x'
        self.pickle_test(pickler, x)
        self.pickle_test(pickler, y)
Ejemplo n.º 7
0
    def search(self, coords, dims):
        """
        Searches all the entries that overlap
        with the given rectangle.
        """
        # Start time
        start = time.clock()

        # Store the results in this list
        results = blist()
        self._search(coords, dims, self.root, results)

        # Get end time
        end = time.clock()

        # Store time
        self.query_times += end - start
        # And increase the inserts counter
        next(self.queries)

        return results
Ejemplo n.º 8
0
def part1(players: int, lastmarble_worth: int) -> int:
    marbles = blist([0])
    scores = {}
    location = 0

    for player in range(1, players + 1):
        scores[player] = 0

    for i in range(1, lastmarble_worth + 1):
        player = players if (i % players) == 0 else (i % players)

        if i % 1000 == 0:
            print(i)

        if i % 23 == 0:
            special_location = location - 7 if location - 7 > 0 else len(
                marbles) + location - 7
            scores[player] += (marbles[special_location]) + i
            del marbles[special_location]
            location = special_location
        else:
            location = 1 if len(marbles) - location == 1 else location + 2
            marbles.insert(location, i)
    return max(scores.values())
Ejemplo n.º 9
0
 def __init__(self):
     self.slist = blist([])
     self.percentiles = [0, 0.25, 0.5, 0.75, 1.0]
     return
Ejemplo n.º 10
0
 def test_types(self):
     type(blist())
     type(iter(blist()))
     type(iter(reversed(blist())))
Ejemplo n.º 11
0
 def test_LIFO(self):
     x = blist()
     for i in range(1000):
         x.append(i)
     for j in range(1000-1,-1,-1):
         self.assertEqual(x.pop(), j)
Ejemplo n.º 12
0
from blist import *

step = 369
pos = 0

buff = blist([0])
for i in range(1, 50000001):
    pos = (pos + step) % len(buff)
    buff.insert(pos + 1, i)
    pos += 1
    if i % 1000000 == 0:
        print(i)
print(buff[pos + 1])
print(buff[buff.index(0) + 1])
Ejemplo n.º 13
0
from blist import *

MAX_MARBLE = 71646 * 100  # 71646 for part one, 71646 * 100 for part 2
PLAYER_COUNT = 412

players = {p: 0 for p in range(PLAYER_COUNT)}
player = 0
# Initialize the game state to the fourth turn to side step edge cases
marbles = blist([0, 2, 1, 3])  # Using blist for better list insert performance
curr = 3

# Start the game
for i in range(4, MAX_MARBLE):
    if i % 23 == 0:
        # Find the node 7 places counter-clockwise from the current node
        target = curr - 7
        if target < 0:
            target = len(marbles) - abs(curr - 7)
        # Update the player's score
        players[player] += (i + marbles[target])
        # Delete the target node
        del marbles[target]
        # Curr becomes the node that is now at the target position (ie the node after the node that was just deleted)
        curr = target
    else:
        # Insert a node between curr+1 and curr+2
        curr += 2
        if curr > len(marbles):
            curr = 1
        marbles.insert(curr, i)
Ejemplo n.º 14
0
import sys
import re
from blist import *

line_re = re.compile('^(\d+) players; last marble is worth (\d+) points$')
m = line_re.search(next(open('input')))
nplayers = int(m.group(1))
last_marble_points = int(m.group(2)) * 100

a = blist([0])
pos = 0
player = 0
player_scores = [0 for _ in range(nplayers)]
for points in range(1, last_marble_points):
    if points % 1000 == 0:
        sys.stdout.write('.')
        sys.stdout.flush()
    player = (player + 1) % nplayers
    if points % 23 == 0:
        pos = (pos - 7) % len(a)
        player_scores[player] += points + a[pos]
        a = a[:pos] + a[pos + 1:]
    else:
        pos = (pos + 2) % len(a)
        if pos == 0:
            a.append(points)
            pos = len(a) - 1
        else:
            a.insert(pos, points)

print
Ejemplo n.º 15
0
    def split_node(self, a):
        # Increment the partition counter
        next(self.partitions)

        # "Copy" the node
        b = Node(a.coords, a.dims, a.leaf)

        # This increments the number of nodes
        if a.leaf:
            next(self.leaf_node_counter)
        else:
            next(self.internal_node_counter)

        # Make sure the copy points to the parent
        b.parent = a.parent

        # Make a pair, the node and the copy
        nn = (a, b)

        # Add the new node the children of the parent too
        if b.parent is not None:
            b.parent.children.append(b)

        # Make a copy of the children
        cc = blist(a.children)

        # Clear the children of the node
        del a.children[:]

        # Nodes picked from the method
        ss = self.pick_seed(cc)

        a.children.append(ss[0])
        b.children.append(ss[1])

        self.tighten(a, b)

        while cc:
            if len(a.children) >= self.m and \
                    len(b.children) + len(cc) == self.m:
                b.children.extend(cc)
                del cc[:]
                self.tighten(a, b)
                return nn
            elif len(b.children) >= self.m and \
                    len(a.children) + len(cc) == self.m:
                a.children.extend(cc)
                del cc[:]
                self.tighten(a, b)
                return nn

            c = self.pick_next(cc, nn)

            preferred = None
            e0 = self.get_required_expansion(a.coords, a.dims, c)
            e1 = self.get_required_expansion(b.coords, b.dims, c)

            if e0 < e1:
                preferred = a
            elif e0 > e1:
                preferred = b
            else:
                a0 = self.get_area(a.dims)
                a1 = self.get_area(b.dims)

                if a0 < a1:
                    preferred = a
                elif e0 > a1:
                    preferred = b
                else:
                    if len(a.children) < len(b.children):
                        preferred = a
                    elif len(a.children) > len(b.children):
                        preferred = b
                    else:
                        preferred = random.choice(nn)

            preferred.children.append(c)
            self.tighten(preferred)

        return nn
Ejemplo n.º 16
0
# I gave up on Haskell for this one after I spent hours optimizing...

from blist import *

numPlayers = 458
numBalls = 7130700

scores = blist([0] * numPlayers)
balls = blist([0])
lastPos = 0

for i in range(1, numBalls):
    if (i % 1000 == 0):
        print(i, numBalls)
    player = i % numPlayers
    #    print(i, lastPos, player, scores, balls)
    if (i % 23) == 0:
        lastPos = (lastPos - 7) % len(balls)
        scores[player] += i
        scores[player] += balls[lastPos]
        del balls[lastPos]
    else:
        lastPos = 1 + (lastPos + 1) % (len(balls))
        balls.insert(lastPos, i)
#print(i, lastPos, player, scores, balls)

print(max(scores))
Ejemplo n.º 17
0
 def test_sort_twice(self):
     y = blist(list(range(limit+1)))
     for i in range(2):
         x = blist(y)
         x.sort()
         self.assertEqual(tuple(x), tuple(range(limit+1)))
Ejemplo n.º 18
0
    def __init__(self, dmbname, throttle=False, verbose=False, string_mode=string_mode_default, check_string_crc=False):
        self.string_mode = string_mode if string_mode != string_mode_default else string_mode_byte_strings
        self.check_string_crc = check_string_crc
        self.reader = open(dmbname, 'rb')
        self.bit32 = False
        self.throttle = throttle
        self.ops = 0
        self.world = WorldData()
        self._parse_version_data()
        if verbose:
            print("Compiled with byond {0} (requires {1} server, {2} client)".format(self.world.world_version, self.world.min_server, self.world.min_client))

        self.flags = self._uint32()
        self.world.map_x, self.world.map_y, self.world.map_z = (self._uint16(), self._uint16(), self._uint16())
        self.bit32 = (self.flags & 0x40000000) > 0

        if verbose:
            print("{0}-bit dmb".format(32 if self.bit32 else 16))

        tilegen = TileGenerator(self, self.world.map_x * self.world.map_y * self.world.map_z)
        self.tiles = [[[tile for tile in tilegen.gen(self.world.map_x)] for j in range(self.world.map_y)] for i in range(self.world.map_z)]
        self._uint32()  # drop this

        self.no_parent_type = Type("/", None)

        type_count = self._uarch()
        if verbose:
            print("{0} types ({1})".format(type_count, hex(self.reader.seek(0, io.SEEK_CUR))))
        self.types = blist([t for t in self._typegen(type_count)])

        mob_count = self._uarch()
        if verbose:
            print("{0} mobs ({1})".format(mob_count, hex(self.reader.seek(0, io.SEEK_CUR))))
        self.mobs = blist([m for m in self._mobgen(mob_count)])

        self.strcrc = np.uint32(0)
        string_count = self._uarch()
        if verbose:
            print("{0} strings".format(string_count))
        self.strings = blist([s for s in self._stringgen(string_count)])
        crc = self._uint32()  # CRC
        if self.check_string_crc:
            if crc != self.strcrc:
                raise DmbFileError("String table CRC mismatch (expected: {0}, got: {1})".format(crc, self.strcrc))
            elif verbose:
                print("String table CRC check passed.")

        data_count = self._uarch()
        if verbose:
            print("{0} data".format(data_count))
        self.data = blist([d for d in self._datagen(data_count)])

        proc_count = self._uarch()
        if verbose:
            print("{0} procs".format(proc_count))
        self.procs = blist([p for p in self._procgen(proc_count)])

        var_count = self._uarch()
        if verbose:
            print("{0} vars".format(var_count))
        self.variables = blist([v for v in self._vargen(var_count)])

        argproc_count = self._uarch()
        if verbose:
            print("{0} argprocs".format(argproc_count))
        self.argprocs = blist([v for v in self._argprocgen(argproc_count)])

        instance_count = self._uarch()
        if verbose:
            print("{0} instances".format(instance_count))
        self.instances = blist([i for i in self._instancegen(instance_count)])

        mappop_count = self._uint32()
        if verbose:
            print("{0} mappops".format(mappop_count))
        self._populate_map(mappop_count)

        self._parse_extended_data()

        res_count = self._uarch()
        if verbose:
            print("{0} resources".format(res_count))
        self.resources = blist([r for r in self._resourcegen(res_count)])

        self.reader.close()
        self.reader = None