예제 #1
0
 def test_node_repr(self):
     a = dllist([None]).first
     self.assertEqual(repr(a), '<dllistnode(None)>')
     b = dllist([1, None]).first
     self.assertEqual(repr(b), '<dllistnode(1)>')
     c = dllist(['abc', None]).first
     self.assertEqual(repr(c), '<dllistnode(\'abc\')>')
예제 #2
0
    def transition(self, state):
        assert len(state) == num_cars
        state = np.array(state)

        state_current = dllist(state)
        state_old = state_current
        state_current = dllist()

        # update the state
        for car in llist_generator(state_old):
            ita = np.random.randn() * v_error
            #print(ita)
            if car is state_old.first:
                # first car, always cruise
                position = car.value + v_cruise + ita
                state_current.append(position)
                # step_desc += 'first'
            else:
                # not the first car
                distance = car.prev.value - car.value
                p = prob_close if distance < threshold_close else prob_fine if distance < threshold_far else prob_far

                v = np.random.choice(velocities, p=p)
                position = car.value + v + ita
                state_current.append(position)
        state = list(state_current)
        return state
예제 #3
0
 def test_insertafter_with_invalid_ref_node(self):
     ll = dllist()
     other_list = dllist(['node in other list'])
     self.assertRaises(TypeError, ll.insertafter, 1234, None)
     self.assertRaises(TypeError, ll.insertafter, 1234, 'not a dllist node')
     self.assertRaises(ValueError, ll.insertafter, 1234, dllistnode())
     self.assertRaises(ValueError, ll.insertafter, 1234, other_list.first)
예제 #4
0
 def test_node_str(self):
     a = dllist([None, None]).first
     self.assertEqual(str(a), 'dllistnode(None)')
     b = dllist([1, None]).first
     self.assertEqual(str(b), 'dllistnode(1)')
     c = dllist(['abc', None]).first
     self.assertEqual(str(c), 'dllistnode(abc)')
예제 #5
0
 def __init__(self, cards: np.ndarray, player_sid: str) -> None:
     self._num_cards = 0
     self._cards = np.empty(shape=53, dtype=np.object)
     for card in cards:
         self[card] = dllist()  # a dllist of HandPointerNodes
         self._num_cards += 1
     self._hands: dllist = dllist()  # a dllist of ConsciousHandNodes
     self._player_sid = player_sid
예제 #6
0
 def test_insertnodeafter_adds_node_in_correct_position(self):
     ll = dllist([0, 1, 2, 3, 4])
     inserted_node = dllistnode(1234)
     ref_node = ll.nodeat(2)
     ll.insertnodeafter(inserted_node, ref_node)
     self.assertIs(ll.nodeat(3), inserted_node)
     self.assertIs(ll.nodeat(3).value, inserted_node.value)
     self.assertEqual(ll, dllist([0, 1, 2, 1234, 3, 4]))
예제 #7
0
 def test_insertafter_extracts_value_from_inserted_node(self):
     ll = dllist([0])
     free_node = dllistnode('free node')
     other_list = dllist(['node in other list'])
     new_node = ll.insertafter(free_node, ll.first)
     self.assertIsNot(new_node, free_node)
     self.assertIs(new_node.value, free_node.value)
     new_node = ll.insertafter(other_list.first, ll.first)
     self.assertIsNot(new_node, other_list.first)
     self.assertIs(new_node.value, other_list.first.value)
예제 #8
0
 def __init__(self):
     self.directions = dllist([{'dx': 0, 'dy': 1, 'dir': ' ^ '}, {'dx': -1, 'dy': 0, 'dir': ' > '},
                               {'dx': 0, 'dy': -1, 'dir': ' v '}, {'dx': 1, 'dy': 0, 'dir': ' < '}])
     self.direction = self.directions[0]
     _coords_list = [i for i in range(0, 35)]
     self.x_coordinates_list = dllist(_coords_list)
     self.y_coordinates_list = dllist(_coords_list)
     self.x_coordinates_list.rotate(16)
     self.y_coordinates_list.rotate(16)
     self.place = [self.y_coordinates_list[0], self.x_coordinates_list[0]]   # [17, 17]
예제 #9
0
    def __init__(self, **kwargs):
        self.PLEASE_SET_k = -1

        self.T1 = dllist()
        self.T2 = dllist()
        self.B1 = dllist()
        self.B2 = dllist()
        self.p = 0
        self.shadow_cache = {}

        self.name = "ARC"
예제 #10
0
 def __init__(self, seed_customers, D, d):
     self.potential_insertions = []
     if seed_customers:
         lroute = [0] + seed_customers + [0]
         self.route = dllist(lroute)
         self.cost = objf(lroute, D)
         self.used_capacity = sum(d[n] for n in lroute) if d else 0
     else:
         self.route = dllist([0, 0])
         self.used_capacity = 0
         self.cost = 0
예제 #11
0
 def full_reset_node(self):
     self.full_children = dllist()
     self.partial_children = dllist()
     self.pertinent_child_count = 0
     self.pertinent_leaf_count = 0
     self.mark = Mark.UNMARKED
     self.label = Label.EMPTY
     self.clear_siblings()
     self.clear_endmost()
     self.circular_link = dllist()
     self.is_pseudo_node = False
예제 #12
0
 def test_concat(self):
     a_ref = py23_range(0, 1024, 4)
     a = dllist(a_ref)
     b_ref = py23_range(8092, 8092 + 1024, 4)
     b = dllist(b_ref)
     ab_ref = dllist(a_ref + b_ref)
     c = a + b
     self.assertEqual(c, ab_ref)
     self.assertEqual(len(c), len(ab_ref))
     c = a + b_ref
     self.assertEqual(c, ab_ref)
     self.assertEqual(len(c), len(a_ref) * 2)
예제 #13
0
 def test_concat_empty(self):
     empty = dllist()
     filled_ref = py23_range(0, 1024, 4)
     filled = dllist(filled_ref)
     res = empty + empty
     self.assertEqual(res, dllist([] + []))
     self.assertEqual(len(res), 0)
     res = empty + filled
     self.assertEqual(res, dllist([] + filled_ref))
     self.assertEqual(len(res), len(filled_ref))
     res = filled + empty
     self.assertEqual(res, dllist(filled_ref + []))
     self.assertEqual(len(res), len(filled_ref))
예제 #14
0
 def test_insert_node_value_before_first(self):
     ll = dllist(py23_xrange(4))
     ref = dllist([10, 0, 1, 2, 3])
     next = ll.nodeat(0)
     arg_node = dllistnode(10)
     new_node = ll.insertnode(arg_node, ll.nodeat(0))
     self.assertEqual(new_node, arg_node)
     self.assertEqual(new_node.value, 10)
     self.assertEqual(new_node.prev, None)
     self.assertEqual(new_node.next, next)
     self.assertEqual(next.prev, new_node)
     self.assertEqual(new_node, ll.first)
     self.assertEqual(ll, ref)
예제 #15
0
 def test_appendleft(self):
     ll = dllist(py23_xrange(4))
     ref = dllist([10, 0, 1, 2, 3])
     next = ll.nodeat(0)
     arg_node = dllistnode(10)
     new_node = ll.appendleft(arg_node)
     self.assertNotEqual(new_node, arg_node)
     self.assertEqual(new_node.value, 10)
     self.assertEqual(new_node.prev, None)
     self.assertEqual(new_node.next, next)
     self.assertEqual(next.prev, new_node)
     self.assertEqual(ll.first, new_node)
     self.assertEqual(ll, ref)
예제 #16
0
 def test_appendright(self):
     ll = dllist(py23_xrange(4))
     ref = dllist([0, 1, 2, 3, 10])
     prev = ll.nodeat(-1)
     arg_node = dllistnode(10)
     new_node = ll.appendright(arg_node)
     self.assertNotEqual(new_node, arg_node)
     self.assertEqual(new_node.value, 10)
     self.assertEqual(new_node.prev, prev)
     self.assertEqual(new_node.next, None)
     self.assertEqual(prev.next, new_node)
     self.assertEqual(ll.last, new_node)
     self.assertEqual(ll, ref)
예제 #17
0
    def reset(self):
        if self.node_type != Type.LEAF:
            for child in self.iter_children():
                child.reset()

        # Common part for all nodes
        self.full_children = dllist()
        self.partial_children = dllist()
        self.pertinent_child_count = 0
        self.pertinent_leaf_count = 0
        self.mark = Mark.UNMARKED
        self.label = Label.EMPTY
        self.is_pseudo_node = False
예제 #18
0
 def test_insert_node_value_before(self):
     ll = dllist(py23_xrange(4))
     ref = dllist([0, 1, 10, 2, 3])
     prev = ll.nodeat(1)
     next = ll.nodeat(2)
     arg_node = dllistnode(10)
     new_node = ll.insertnode(arg_node, ll.nodeat(2))
     self.assertEqual(new_node, arg_node)
     self.assertEqual(new_node.value, 10)
     self.assertEqual(new_node.prev, prev)
     self.assertEqual(new_node.next, next)
     self.assertEqual(prev.next, new_node)
     self.assertEqual(next.prev, new_node)
     self.assertEqual(ll, ref)
예제 #19
0
    def template_p3(self, node: PQnode) -> bool:
        if node.node_type != Type.P_NODE or len(node.partial_children) > 0:
            #print("[Template_P3] result = " + str(False) + " node: " + str(node.id))
            return False

        new_qnode = PQnode()
        new_qnode.node_type = Type.Q_NODE
        new_qnode.label = Label.PARTIAL
        self.pertinent_nodes.append(new_qnode)

        node.parent.replace_partial_child(node, new_qnode)
        node.replace_direction_indicator(new_qnode)

        # Special case when only one full child
        if len(node.full_children) == 1:
            full_child = node.full_children.nodeat(0).value
            node.full_children = dllist()
            node.circular_link.remove(full_child.circular_list_node)
        # Otherwise create new P-node
        else:
            full_child = PQnode()
            full_child.node_type = Type.P_NODE
            node.move_full_children(full_child)

        full_child.parent = new_qnode
        new_qnode.endmost_children[0] = full_child
        full_child.mark_full()
        self.pertinent_nodes.append(full_child)

        # If only one empty child
        if len(node.circular_link) - len(node.full_children) == 1:
            empty_child = node.circular_link.nodeat(0).value
            node.circular_link = dllist()
        else:
            empty_child = node

        empty_child.parent = new_qnode
        new_qnode.endmost_children[1] = empty_child
        empty_child.mark_empty()

        empty_child.immediate_sublings[0] = full_child
        full_child.immediate_sublings[0] = empty_child

        new_qnode.mark_partial()
        self.pertinent_nodes.append(new_qnode)
        #print("Template 3 exit with True node: " + str(node.id))

        return True
예제 #20
0
    def test_iternodes_with_removed_node(self):
        ll = dllist(['x', 'removed item'])
        removed_node = ll.last

        for node in ll.iternodes():
            self.assertNotEqual(node, removed_node)
            ll.remove(removed_node)
예제 #21
0
 def test_node_owner(self):
     ll = dllist([1234])
     owner_ref = ll.first.owner
     self.assertIsInstance(owner_ref, weakref.ref)
     self.assertIs(owner_ref(), ll)
     del ll
     self.assertIsNone(owner_ref())
예제 #22
0
 def test_remove_after_remove(self):
     ll = dllist([1, 2, 3])
     del_node = ll.nodeat(1)
     ll.remove(del_node)
     self.assertIs(del_node.prev, None)
     self.assertIs(del_node.next, None)
     self.assertIs(del_node.owner, None)
예제 #23
0
 def test_insertnodeafter_returns_inserted_node(self):
     ll = dllist([0])
     inserted_value = 'inserted value'
     inserted_node = dllistnode(inserted_value)
     returned_node = ll.insertnodeafter(inserted_node, ll.first)
     self.assertIs(returned_node, inserted_node)
     self.assertIs(returned_node.value, inserted_value)
예제 #24
0
 def test_node_after_del(self):
     ll = dllist([1, 2, 3])
     del_node = ll.nodeat(1)
     del ll[1]
     self.assertIs(del_node.prev, None)
     self.assertIs(del_node.next, None)
     self.assertIs(del_node.owner, None)
예제 #25
0
 def test_insert_node_with_invalid_ref(self):
     ll = dllist()
     self.assertRaises(TypeError, ll.insertnode, dllistnode(10), 1)
     self.assertRaises(TypeError, ll.insertnode, dllistnode(10), 'abc')
     self.assertRaises(TypeError, ll.insertnode, dllistnode(10), [])
     self.assertRaises(ValueError, ll.insertnode, dllistnode(10),
                       dllistnode())
예제 #26
0
 def test_insertnodeafter_with_invalid_type_of_inserted_node(self):
     ll = dllist([0])
     self.assertRaises(TypeError, ll.insertnodeafter, None, ll.first)
     self.assertRaises(TypeError, ll.insertnodeafter, 'non-node argument',
                       ll.first)
     self.assertRaises(TypeError, ll.insertnodeafter, sllistnode(1234),
                       ll.first)
예제 #27
0
def deepcopy(dllist):
    copy_dllist = linked_list.dllist()
    this = dllist.first
    while this != None:
        copy_dllist.insert(this.value)
        this = this.next
    return copy_dllist
예제 #28
0
 def test_node_after_popright(self):
     ll = dllist([1, 2])
     del_node = ll.last
     ll.popright()
     self.assertIs(del_node.prev, None)
     self.assertIs(del_node.next, None)
     self.assertIs(del_node.owner, None)
예제 #29
0
def refine(partition_class):
    """
    Parameters:
    partition_class -  a partition class with vertices
    stack - a stack is lists of friends"""
    partition = dllist([partition_class])
    partition.first.value.update_partition_class_link(partition.first)

    while partition_class.stack:
        top = partition_class.stack.pop()
        for u in top:
            u.partition_class.value.move_vertex(u)

        for u in top:
            if u.partition_class.value.splittable:
                u.partition_class.value.splittable = False
                left = u.partition_class.value.split()
                u.partition_class = partition.insert(PartitionClass(left),
                                                     u.partition_class)
                u.partition_class.value.update_partition_class_link(
                    u.partition_class)

    for partition_class in partition:
        for u in partition_class.elements:
            u.refined = True

    return [partition_class.elements for partition_class in partition]
예제 #30
0
 def test_rotate_right_empty(self):
     for n in py23_xrange(4):
         ll = dllist()
         ll.rotate(n)
         self.assertEqual(ll.first, None)
         self.assertEqual(ll.last, None)
         self.assertEqual(ll.size, 0)
예제 #31
0
파일: judgelist.py 프로젝트: DMOJ/site
 def __init__(self):
     self.queue = dllist()
     self.priority = [self.queue.append(PriorityMarker(i)) for i in range(self.priorities)]
     self.judges = set()
     self.node_map = {}
     self.submission_map = {}
     self.lock = RLock()
예제 #32
0
 def do_once(self):
     dlist = dllist(xrange(0, 40))
     while True:
         try:
             dlist.pop()
         except ValueError:
             return
         dlist.rotate(3)
예제 #33
0
 def __init__(self, unskilled_score=None, variance=None, backlog_history=None, single_version=False):
     super(Pool, self).__init__(single_version)
     self.workers = set()
     self.nworkers = 0
     self.unskilled = llist.dllist()
     self.skilled = {}  # rclass -> {[(score, workers)]}
     self.event = gevent.event.Event()
     _init_backlog(self)
     self.update_settings(dict(unskilled_score=unskilled_score, variance=variance, backlog_history=backlog_history))
예제 #34
0
파일: timer.py 프로젝트: eadamsatx/freepy
  def __create_vector__(self, size):
    '''
    Creates a new vector and initializes it to a specified size.

    Arguments: size - The size of the vector.
    '''
    vector = list()
    for counter in range(size):
      vector.append(dllist())
    return vector
예제 #35
0
파일: Scenario.py 프로젝트: sernst/Cadence
    def __init__(self, trackway, path):
        """ A Scenario is built around the dictionary entries, which
            consists of four keys corresponding to the four limbs ('lp', 'rp',
            'lm', and 'rm').  The value associated with each key is a doubly-
            linked list (dllist) of entries, which comprise an ordered sequence
            of tracks.  Each entry is a dictionary of six key-value pairs:
            the name, uid, x, y, dx, and dy for a given track.  Each of the four
            sequences represents an an hypothesized sequence of tracks created
            by one limb ('lp', say).  Each track sequence can be edited to
            modify the contents of any entry, or to add/remove entries. """

        self.entries = dict(
            lp=dllist(),
            rp=dllist(),
            lm=dllist(),
            rm=dllist())

        self.trackway = trackway

        self.load(trackway, path)
예제 #36
0
def generate_lucky_list(max_num):
    lucky_numbers = dllist(range(1, max_num + 1, 2))

    multiple_node = lucky_numbers.nodeat(1)

    while multiple_node != None:
        removed_multiple = multiple_node()
        if removed_multiple >= len(lucky_numbers):
            break

        removed_pos = removed_multiple - 1
        while removed_pos < len(lucky_numbers):
            del lucky_numbers[removed_pos]
            removed_pos += removed_multiple - 1

        multiple_node = multiple_node.next

    return lucky_numbers
예제 #37
0
파일: lb.py 프로젝트: jamur2/zc.resumelb
    def __init__(self,
                 unskilled_score=None, variance=None, backlog_history=None,
                 single_version=False):
        self.workers = set()
        self.nworkers = 0
        self.unskilled = llist.dllist()
        self.skilled = {}   # rclass -> {[(score, workers)]}
        self.event = gevent.event.Event()
        _init_backlog(self)
        self.single_version = single_version
        if single_version:
            # {version -> {worker}}
            self.byversion = collections.defaultdict(set)
            self.version = None

        self.update_settings(dict(
            unskilled_score=unskilled_score,
            variance=variance,
            backlog_history=backlog_history))
예제 #38
0
def main():
	# I import the list, node to insert and node to delete as they were initialized in main
	setup = """\
from __main__ import lst, nodeDel, nodeIns
"""
	# Saving running times to a file
	f = open('delete.csv','w')
	g = open('insert.csv','w')
	
	# Using large enough data structure sizes to observe any differences
	for i in range(20000,100000,1000):
		# The global keyword is needed as I modify global variables
		global lst; global nodeDel; global nodeIns

		sys.stderr.write(str(i)+"\n")
		# Initializing the doubly linked list
		size = i; values=randomvalues(size)
		lst=dllist(values)

		delTime = 0; insTime = 0
		# I measure average times of 100 runs
		for jj in range(100):
			# Pick random integers with linked list range for inserting and deleting
			valueToDelete=randint(0,size-1)
			valueToInsert=randint(0,size-1)
			nodeDel = lst.nodeat(valueToDelete)
			nodeIns = lst.nodeat(valueToInsert)

			try:
				# Measure delete time and then insert the deleted node to keep linked list size constant
    				t=timeit.Timer(stmt="lst.remove(nodeDel)",setup=setup)
				delTime += t.timeit(number=1); lst.insert(values[valueToDelete])
				# Measure insert time and then delete the inserted item to keep linked list size constant
    				t2=timeit.Timer(stmt="lst.insert(nodeIns)",setup=setup)
				insTime += t2.timeit(number=1); lst.remove(nodeIns)
			except ValueError:
				# Sometimes there are errors, ignoring those
				sys.stderr.write("Broken at "+str(i)+"\n")
				continue
		
		# Save average results to a file
    		g.write(str(i)+"\t"+str(1000*insTime/100)+"\n")
		f.write(str(i)+"\t"+str(1000*delTime/100)+"\n")
예제 #39
0
 def __init__(self):
     self.main_stack = dllist()
     self.min_stack = []
예제 #40
0
 def __init__(self, single_version=False):
     super(ClasslessPool, self).__init__(single_version)
     self.backlog = 0
     self.workers = set()
     self.line = llist.dllist()
     self.event = gevent.event.Event()
def bottom_up(data, k, calc_error=sqr_residual, max_error=float('inf')):
    '''
    Merge time series data points to produce trend segments
    using bottom-up method where k is the average segment length.

    The data should be a list of values.

    Terminates when average segment length is more than k.
    
    OR 
    
    If max_error > 0, when the maximum error of any 
    segment (in terms of a residual with the original data underlying the 
    segment) has reached the limit.

    calc_error(segment, data) provides the specific implementation to
    compute the error of a segment.
    
    Returns a subset of the data in the form of [(index, value)].
    '''

    ## INITIALIZATION STEP
    n = len(data)

    # split into segments of length 2
    # a segment is of the form ((index, value), (index, value))
    segments = [((2*i,data[2*i]), (2*i+1,data[2*i+1])) for i in xrange(n/2)]

    # create linked list of pairs of segments
    # and a heap dictionary of (pair -> residual error) 
    pairs = llist.dllist()
    res_heap = hd.heapdict()

    for i in xrange(len(segments)-1):
        # create the pair
        left = segments[i]
        right = segments[i+1]
        seg_pair = (left, right)
        
        # get the residual error
        res = calc_error(merge_segs(left, right), data)

        # add to linked list and heap
        node = pairs.append(seg_pair)
        res_heap[node] = res

    ## MERGE STEP
    # merge segments while number of segments at most n/k
    while len(pairs) > n/k:
        pair, res = res_heap.popitem()
        if res > max_error:
            break

        new_seg = merge_segs(pair.value[0], pair.value[1])

        # update second segment of left pair in linked list and also
        # delete old left pair from heap and re-add new pair with new res
        left = pair.prev
        if left != None:
            del res_heap[left]
            lpair = left.value
            left.value = (lpair[0], new_seg)
            merged = merge_segs(left.value[0], left.value[1])
            res_heap[left] = calc_error(merged, data)

        # update first segment of right pair
        right = pair.next
        if right != None:
            del res_heap[right]
            rpair = right.value
            right.value = (new_seg, rpair[1])
            merged = merge_segs(right.value[0], right.value[1])
            res_heap[right] = calc_error(merged, data)

        # remove old pair from pairs linked list
        pairs.remove(pair)


    # form a list of (index, value) keeping 
    # only the values after being segmented
    segmented_data = []

    # retrieve unique segments
    head = pairs.first
    while head != None:
        unique_seg = head.value[0]
        segmented_data.append(unique_seg[0])
        segmented_data.append(unique_seg[1])
        head = head.next

    # add the last data point
    segmented_data.append(pairs.last.value[1][1])

    return segmented_data
예제 #42
0
 def __init__(self, logger = None, size = 2):
     log = logger
     self._size = size
     self._hash_map = {}
     self._queue = dllist()
예제 #43
0
from llist import dllist, dllistnode
import time
base_ls=[1,2,3,4,5,6]
lst=dllist(base_ls)
nod=lst.first
def dis():
    if(len(base_ls)==0):
        print("Empty Linked_list")
        proceed()
    else:
        print("Display Linked_list")
        for i in range(len(base_ls)):
            print("Key-->",i,"Value-->",base_ls[i])
        print(lst)
        proceed()
def inser():
    print("---------------------------------------------------------------------------")
    print("Select Your Option:\n---------------------------------------------------------------------------")
    print("1.Insert at begin.|\t2.Insert at Last.|\t3.Insert in Between.\n---------------------------------------------------------------------------")
    sam=int(raw_input("Enter your option:"))
    if(sam==1):
        a=input("Enter the Value to insert:")
        print("Before Insert:",lst)
        lst.appendleft(a)
        
        print("After Insert:",lst)
        proceed()
    elif(sam==2):
        a=input("Enter the Value to insert:")
        print("Before Insert:",lst)
        lst.appendright(a)
예제 #44
0
    def __init__(self):
        if dllist is None:
            raise Exception('Unable to construct lru:// - "llist" and "pyllist" modules are not available')

        self._list = dllist()
        self._lock = Lock()
예제 #45
0
	         lru.checkempty(app_launched)
	    
	    historylist.appendleft(app_launched)
    
    
    def readinglogs(self, maxsize, filename):
        '''Reading the log file'''
        txt = open(filename)
        print "The log file used is %r: " % filename
	global logs
        logs = [line.strip() for line in open(filename)]
       # print '\n'.join(logs)
	lru.pushapplications(maxsize,logs)

	
if __name__ == "__main__":
    lru = LruCache()
    dlist = dllist()
    historylist = dllist()
    script, filename = argv
    maxsize =16
    lru.readinglogs(maxsize, filename)
    print '#' * 80
    print 'Final Contents of Stack   => \n',dlist
    print 'Stack Size                = ',dlist.size
    print 'Total hits                = ', hits
    print 'Total misses              = ', misses
    print 'Total Application Reboots = ', reboots
    print '#' * 80

예제 #46
0
 def push(self, x):
     """Push element x onto the heap."""
     self._root = _meld(self._root, _Node(x, dllist()))
     self._nelems += 1
     if x is not self._root.key:      #returns ref to dllistnode
         return self._root.sub.last   #in which x is now