Python:Chain Construction

import numpy as np
from collections import OrderedDict
from copy import deepcopy


class Chain(object):
    def __init__(self,idx):
        self.idx = idx
        self.lead = None
        self.follow = None
        self.same = None


a = [4,5,3,2,1,7,9]

chainSet = OrderedDict()
for ele in a:
    chainSet[ele] = Chain(ele)

for i in range(len(chainSet)-1):
    if a[i] < a[i+1]:
        chainSet[a[i]].follow = chainSet[a[i+1]].idx
        chainSet[a[i + 1]].lead = chainSet[a[i]].idx
    elif a[i] > a[i+1]:
        chainSet[a[i]].lead = chainSet[a[i+1]].idx
        chainSet[a[i + 1]].follow = chainSet[a[i]].idx
    else:
        chainSet[a[i]].same = chainSet[a[i+1]].idx
        chainSet[a[i + 1]].same = chainSet[a[i]].idx


ChainList = []
for idx, obj in chainSet.items():
    L = []
    L.append(obj.idx)
    abj = deepcopy(obj)
    while abj.lead != None:
        lead = abj.lead
        L.insert(0,lead)
        abj = chainSet[lead]
    abj = deepcopy(obj)
    while abj.follow != None:
        follow = abj.follow
        L.append(follow)
        abj = chainSet[follow]
    ChainList.append(L)
    print(ChainList)

print(set(ChainList))

使用结构体构造链

你可能感兴趣的:(Python学习,算法)