Пример #1
0
def reverse(linked_list):
    tail_pos = linked_list.head
    reversed_linked_list = LinkedList()

    if tail_pos is None:
        return None

    while tail_pos:
        value = tail_pos.value
        reversed_linked_list.prepend(value)
        tail_pos = tail_pos.next

    return reversed_linked_list
Пример #2
0
 def test_1(self):
     ll = LinkedList()
     node1 = Node(1)
     node2 = Node(2)
     node3 = Node(3)
     node4 = Node(4)
     node5 = Node(5)
     ll.append_node(node1)
     ll.append_node(node2)
     ll.append_node(node3)
     ll.append_node(node4)
     ll.append_node(node5)
     reverse_linklist(ll)
     ll.print()
Пример #3
0
 def test_1(self):
     ll = LinkedList()
     ll.append(1)
     ll.append(2)
     ll.append(3)
     ll.append(4)
     ll.append(5)
     self.assertEqual(find_kth_to_tail(ll, 2), 4)
Пример #4
0
def solve_part2(inp: str) -> int:
    cups = []
    for d in inp[:-1]:
        cups.append(int(d))
    for x in range(len(cups) + 1, 1000001):
        cups.append(x)

    llist = LinkedList(cups)
    current = llist.values[cups[0]]
    # Create a circle in the linked list
    llist.values[1000000].next = current

    for _ in range(10000000):
        tmp = current
        picked = []
        for _ in range(3):
            tmp = tmp.next
            picked.append(tmp)
        current.next = picked[2].next

        destination = current.val - 1
        while destination in picked or destination < 1:
            destination -= 1
            if destination < 1:
                destination = 1000000

        picked[2].next = llist.values[destination].next
        llist.values[destination].next = picked[0]

        current = current.next

    node_1 = llist.values[1]
    return node_1.next.val * node_1.next.next.val
Пример #5
0
 def __init__(self, *target_symbols, **kwargs):
     self.trading_days = list()
     self.builder = deque()
     self.composites = LinkedList(*[Node(self)] * 2)
     self._dynamic_universe = {}
     self.symbol_collection = set(target_symbols)
     static_universe = kwargs.get('static_universe')
     self.static_collection = set(
         static_universe) if static_universe else set()
     self.full_universe = set()
     self._previous_trading_day_map = dict()
     self.symbol_data = defaultdict(dict)
     self.static_universe = defaultdict(set)
     self.dynamic_universe = defaultdict(set)
     self.dynamic_universe_ranked = []
     self.cached_factor_data = {}
     self.st_dict = defaultdict(set)
     self.industry_dict = defaultdict(set)
     self.untradable_dict = defaultdict(set)
Пример #6
0
 def test_1(self):
     ll = LinkedList()
     node1 = Node(1)
     node2 = Node(2)
     node3 = Node(3)
     node4 = Node(4)
     node5 = Node(5)
     ll.append_node(node1)
     ll.append_node(node2)
     ll.append_node(node3)
     ll.append_node(node4)
     ll.append_node(node5)
     ll.append_node(node3)
     self.assertEqual(get_length_of_loop_link(ll), 3)
Пример #7
0
def merge(ll1, ll2):
    ll = LinkedList()

    c1 = ll1.head
    c2 = ll2.head

    while c1 and c2:
        if c1.get_data() < c2.get_data():
            ll.append(c1.get_data())
            c1 = c1.get_next()
        else:
            ll.append(c2.get_data())
            c2 = c2.get_next()

    while c1:
        ll.append(c1.get_data())
        c1 = c1.get_next()

    while c2:
        ll.append(c2.get_data())
        c2 = c2.get_next()
    return ll
Пример #8
0
def solve_part1_ll(inp: str) -> int:
    cups = []
    for d in inp[:-1]:
        cups.append(int(d))

    llist = LinkedList(cups)
    current = llist.values[cups[0]]
    # Create a circle in the linked list
    llist.values[cups[8]].next = current

    for _ in range(100):
        # for _ in range(10):
        tmp = current
        picked = []
        for _ in range(3):
            tmp = tmp.next
            picked.append(tmp)
        current.next = picked[2].next

        destination = current.val - 1
        while destination in picked or destination < 1:
            destination -= 1
            if destination < 1:
                destination = 9

        picked[2].next = llist.values[destination].next
        llist.values[destination].next = picked[0]

        current = current.next

    node = llist.values[1]
    r = ""
    for _ in range(8):
        node = node.next
        r += str(node.val)
    return int(r)
Пример #9
0
from utils.linked_list import LinkedList


def iscircular(linked_list):
    if linked_list.head is None:
        return False

    slow = linked_list.head
    fast = linked_list.head

    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next

        if slow == fast:
            return True

    return False


linked_list = LinkedList()

list1 = [-2, -1, 0, 1, 2]
for v in list1:
    linked_list.append(v)

assert iscircular(linked_list) is False
linked_list.head.next = linked_list.head
assert iscircular(linked_list) is True
Пример #10
0
    def test_1(self):
        ll1 = LinkedList()
        ll1.append(2)
        ll1.append(4)
        ll1.append(6)
        ll1.append(8)
        ll1.append(10)

        ll2 = LinkedList()
        ll2.append(1)
        ll2.append(3)
        ll2.append(5)
        ll2.append(7)
        ll2.append(9)
        ll = merge(ll1, ll2)
        ll.print()
Пример #11
0
class Universe(object):
    """
    提供Universe符号计算逻辑。

    Example:
        >> Universe('HS300') + Universe('ZZ500') + Universe('IF') #定义由沪深300,中证500和沪深300主力合约构成的股票池
        >> Universe(IndSW.JiSuanJiL1).filter_universe(Factor.PE.nsmall(100))
            + StockScreener(Factor.PE.nsmall(100), Universe(IndSW.ChuanMeiL1)) #获取计算机和传媒行业PE最低的10只股票组成的股票池
        说明: StockScreener(factor_filter_condition, universe)和universe.filter_universe(factor_filter_condition)效果是一样的
    """

    # NODE_SYMBOLS = 'SYMBOLS'
    # NODE_ADD = 'ADD'
    # NODE_FILTER = 'FILTER'

    def __init__(self, *target_symbols, **kwargs):
        self.trading_days = list()
        self.builder = deque()
        self.composites = LinkedList(*[Node(self)] * 2)
        self._dynamic_universe = {}
        self.symbol_collection = set(target_symbols)
        static_universe = kwargs.get('static_universe')
        self.static_collection = set(
            static_universe) if static_universe else set()
        self.full_universe = set()
        self._previous_trading_day_map = dict()
        self.symbol_data = defaultdict(dict)
        self.static_universe = defaultdict(set)
        self.dynamic_universe = defaultdict(set)
        self.dynamic_universe_ranked = []
        self.cached_factor_data = {}
        self.st_dict = defaultdict(set)
        self.industry_dict = defaultdict(set)
        self.untradable_dict = defaultdict(set)

    def __add__(self, other):
        if isinstance(other, (str, unicode)):
            other = Universe(other)
        elif isinstance(other, (list, set, tuple)):
            other = Universe(static_universe=other)
        elif isinstance(other, Universe):
            pass
        else:
            raise Exception
        new_universe = Universe()
        new_universe.composites = self.composites + other.composites
        return new_universe

    def __radd__(self, other):
        return self.__add__(other)

    def apply_filter(self, filter_condition, skip_halt=True):
        self.builder.append(
            (BuilderType.APPLY_FILTER, (filter_condition, skip_halt)))
        return self

    def is_st(self, formula):
        self.builder.append((BuilderType.IS_ST, formula))
        return self

    def can_trade(self, formula):
        self.builder.append((BuilderType.CAN_TRADE, formula))
        return self

    def exchange(self, formula):
        self.builder.append((BuilderType.EXCHANGE, formula))
        return self

    def exclude_list(self, formula):
        formula = formula.split(',') if isinstance(formula,
                                                   basestring) else formula
        self.builder.append((BuilderType.EXCLUDE_LIST, formula))
        return self

    def custom_universe(self, formula):
        formula = formula.split(',') if isinstance(formula,
                                                   basestring) else formula
        self.builder.append((BuilderType.CUSTOM_UNIVERSE, formula))
        return self

    def apply_sort(self, filter_condition):
        self.builder.append((BuilderType.APPLY_SORT, filter_condition))
        return self

    def _load_from_subset(self, subset_data):
        """
        Universe接收通过UniverseService传入的数据

        Args:
            subset_data: dict of universe service data
        """
        self.symbol_data['static'] = {
            e: e
            for e in subset_data['all_static_universe']
        }
        self.symbol_data['dynamic'].update(
            subset_data['symbol_collection_dict'])
        self._previous_trading_day_map = subset_data[
            'previous_trading_day_map']
        # self._cached_trading_days = subset_data['_cached_trading_days']
        # self._cached_trading_days_index = subset_data['_cached_trading_days_index']
        # self.stock_list_by_day = subset_data['stock_list_by_day']
        self.untradable_dict = subset_data['untradable_dict']
        self.industry_dict = subset_data['industry_dict']
        self.st_dict = subset_data['st_dict']
        self.cached_factor_data = subset_data['cached_factor_data']

    def load_data_from_service(self, trading_days, from_subset_data=None):
        """
        加载 universe 数据,包括 symbol 数据、辅助性数据

        Args:
            trading_days(list of datetime.datetime): 交易日期
            from_subset_data(dict): load universe所需数据来自传入的subset
        """
        if set(trading_days) <= set(self.trading_days):
            return
        self.trading_days = trading_days
        self.composites.traversal(func=dispatch_trading_days,
                                  trading_days=trading_days)
        self._load_from_subset(from_subset_data)
        self.composites.traversal(func=dispatch_symbol_data,
                                  data=self.symbol_data)
        self.composites.traversal(func=dispatch_auxiliary_data, head=self)

    def build(self):
        """
        构建筛选结果
        """
        def func(node):
            node.obj.pipeline()

        self.composites.traversal(func=func)
        self.static_universe = self.composites.recursive(
            formula=(lambda x, y: operate_or(x, y)),
            formatter=(lambda x: x.obj.static_universe))
        self.dynamic_universe = self.composites.recursive(
            formula=(lambda x, y: operate_or(x, y)),
            formatter=(lambda x: x.obj.dynamic_universe))
        self.full_universe = self.composites.recursive(
            formula=(lambda x, y: operate_or(x, y)),
            formatter=(lambda x: x.obj.full_universe))
        head = self.composites.link_head.obj

    def _expand_custom_universe(self, custom_universe):
        """
        将custom_universe展开,当custom_universe为按日期动态定义时

        Returns: custom_universe

        """
        if custom_universe and isinstance(custom_universe, dict):
            last_universe = set()
            for date in self.trading_days:
                if date not in custom_universe:
                    custom_universe.update({date: last_universe})
                else:
                    custom_universe[date] = set(custom_universe[date])
                    last_universe = custom_universe[date]
        return custom_universe

    def pipeline(self):
        """
        构建个性化 Universe 对象
        """
        builders = filter(lambda x: x[0] != BuilderType.APPLY_SORT,
                          self.builder)
        while builders:
            builder_type, formula = builders.pop(0)
            if builder_type == BuilderType.CUSTOM_UNIVERSE:
                formula = self._expand_custom_universe(formula)
                if formula and len(self.symbol_collection) != 0:
                    self.dynamic_universe = operate_and(
                        self.dynamic_universe, formula)
                    self.static_universe = operate_and(self.static_universe,
                                                       formula)
                else:
                    self.dynamic_universe = operate_or(self.dynamic_universe,
                                                       formula)
                    self.static_universe = operate_or(self.static_universe,
                                                      formula)
            elif builder_type == BuilderType.EXCLUDE_LIST:
                exclude_list = set(formula)
                if exclude_list:
                    self.dynamic_universe = operate_minus(
                        self.dynamic_universe, exclude_list)
                    self.static_universe = operate_minus(
                        self.static_universe, exclude_list)
            elif builder_type == BuilderType.IS_ST:
                if formula is True:
                    self.dynamic_universe = operate_and(
                        target_a=self.dynamic_universe, target_b=self.st_dict)
                    self.static_universe = operate_and(
                        target_a=self.static_universe, target_b=self.st_dict)
                else:
                    self.dynamic_universe = operate_minus(
                        target_a=self.dynamic_universe, target_b=self.st_dict)
                    self.static_universe = operate_minus(
                        target_a=self.static_universe, target_b=self.st_dict)
            elif builder_type == BuilderType.CAN_TRADE:
                if formula is True:
                    self.dynamic_universe = operate_minus(
                        target_a=self.dynamic_universe,
                        target_b=self.untradable_dict)
                    self.static_universe = operate_minus(
                        target_a=self.static_universe,
                        target_b=self.untradable_dict)
        self.full_universe = set()
        for dynamic_universe in self.dynamic_universe.itervalues():
            self.full_universe |= dynamic_universe
Пример #12
0
 def test_2(self):
     ll = LinkedList()
     ll.append(1)
     self.assertEqual(get_length_of_loop_link(ll), -1)
Пример #13
0
from utils.linked_list import LinkedList


# def PrintListReversinglyRecurisively
def print_list_reversingly_recurisively(head):
    if head is None:
        return

    current = head
    next = current.get_next()
    if next is not None:
        print_list_reversingly_recurisively(next)

    print(current.get_data())


if __name__ == '__main__':
    ll = LinkedList()
    ll.append(1)
    ll.append(2)
    ll.append(3)
    ll.append(4)
    ll.append(5)
    # ll.print()

    print_list_reversingly_recurisively(ll.head)
Пример #14
0
def mgm_floyd(X, K, num_graph, num_node):
    """
    :param K: affinity matrix, (num_graph, num_graph, num_node^2, num_node^2)
    :param num_graph: number of graph, int
    :param num_node: number of node, int
    :return: matching results, (num_graph, num_graph, num_node, num_node)
    """

    affinity_matrix = cal_affinity_matrix(X, K, num_graph)
    max = np.max(affinity_matrix)
    min = np.min(affinity_matrix)

    linked_k = LinkedList()
    for i in range(num_graph):
        linked_k.add(i)
    linked_nodes = LinkedList()
    while not linked_k.isEmpty():
        v = linked_k.pop()
        for i in range(v):
            linked_nodes.add(i)
        for i in range(v + 1, num_graph):
            linked_nodes.append(i)
        while not linked_nodes.isEmpty():
            x = linked_nodes.pop()
            for y in range(num_graph):
                # calculate S_org
                J_xy_ori = single_affinity(X[x][y], K[x][y])
                J_xy = (J_xy_ori - min) / (max - min)
                S_org = J_xy

                # calculate S_opt
                X_xv_vy = np.matmul(X[x][v], X[v][y])
                J_xv_vy = (single_affinity(X_xv_vy, K[x][y]) - min) / (max -
                                                                       min)
                S_opt = J_xv_vy

                # compare and update
                if S_org < S_opt:
                    X[x][y] = np.matmul(X[x][v], X[v][y])
                    X[y][x] = np.matmul(X[y][v], X[v][x])
                    if linked_nodes.search(y):
                        linked_nodes.remove(y)
                        linked_nodes.append(y)
                    if linked_k.search(y):
                        linked_k.remove(y)
                        linked_k.append(y)
                    if linked_k.search(x):
                        linked_k.remove(x)
                        linked_k.append(x)
                if J_xy_ori < min:
                    min = J_xy_ori
                elif J_xy_ori > max:
                    max = J_xy_ori

    # set lambda and repeat above process
    Lambda = 0.45
    affinity_matrix = cal_affinity_matrix(X, K, num_graph)
    max = np.max(affinity_matrix)
    min = np.min(affinity_matrix)
    # use unary consistency to speed up
    consistency_matrix = cal_unary_consistency_matrix(X, num_graph, num_node)

    flag = False  # use flag to check whether X is updated
    for i in range(num_graph):
        linked_k.add(i)
    while not linked_k.isEmpty():
        v = linked_k.pop()
        for i in range(v):
            linked_nodes.add(i)
        for i in range(v + 1, num_graph):
            linked_nodes.add(i)
        if flag:
            consistency_matrix = cal_unary_consistency_matrix(
                X, num_graph, num_node)
            flag = False
        while not linked_nodes.isEmpty():
            x = linked_nodes.pop()
            for y in range(num_graph):
                J_xy_ori = single_affinity(X[x][y], K[x][y])
                J_xy = (J_xy_ori - min) / (max - min)
                Cp_xy = consistency_matrix[y]
                S_org = (1 - Lambda) * J_xy + Lambda * Cp_xy

                X_xv_vy = np.matmul(X[x][v], X[v][y])
                J_xv_vy = (single_affinity(X_xv_vy, K[x][y]) - min) / (max -
                                                                       min)
                C_xv_vy = consistency_matrix[v]
                S_opt = (1 - Lambda) * J_xv_vy + Lambda * C_xv_vy

                if S_org < S_opt:
                    X[x][y] = np.matmul(X[x][v], X[v][y])
                    X[y][x] = np.matmul(X[y][v], X[v][x])
                    flag = True
                    if linked_nodes.search(y):
                        linked_nodes.remove(y)
                        linked_nodes.append(y)
                    if linked_k.search(y):
                        linked_k.remove(y)
                        linked_k.append(y)
                    if linked_k.search(x):
                        linked_k.remove(x)
                        linked_k.append(x)
                if J_xy_ori < min:
                    min = J_xy_ori
                elif J_xy_ori > max:
                    max = J_xy_ori
    return X
Пример #15
0
        # 后节点前移
        node.set_data(next.get_data())
        node.set_next(nnext)

        # 其实这里node4的内存是释放不了的,因为之前还存在引用
        # del next
    else:
        # 要删除的是尾节点,从头遍历
        c = linklist.head
        while c.get_next() != node:
            c = c.get_next()
        c.set_next(None)


if __name__ == '__main__':
    ll = LinkedList()
    node1 = Node(1)
    node2 = Node(2)
    node3 = Node(3)
    node4 = Node(4)
    node5 = Node(5)
    ll.append_node(node1)
    ll.append_node(node2)
    ll.append_node(node3)
    ll.append_node(node4)
    ll.append_node(node5)
    delete(ll, node3)
    ll.print()
    print("======")
    delete(ll, node5)
    ll.print()
Пример #16
0
 def test_2(self):
     ll = LinkedList()
     ll.append(1)
     self.assertEqual(find_kth_to_tail(ll, 1), 1)