合适的数据结构

时间:2013-11-28 20:50:35

标签: python data-structures python-3.x

我需要创建一个数据结构,该结构将保存各公司的信息,并遵循以下规则。

如果A公司拥有B公司50%以上的股份,公司A'控制'公司B. 如果公司B拥有公司C中> 50%的股票,则B控制C,A控制B和C. 如果公司A控制公司B,C和D,并且公司E中的B,C和D组合比例加起来大于50%,则公司A拥有公司E.

我已经设法做到这一点,但最后一部分让我搞砸了。到目前为止,我的程序最终会无休止地循环,或者只是在最后一部分不工作。

我意识到这个问题可能有点糟糕,但即使只是朝着正确的方向发展,我也会感激不尽。

1 个答案:

答案 0 :(得分:0)

from collections import defaultdict

def find_controlled(company, shares):
    # shares the company owns directly
    controls = set([company])       # avoid the recursion problem pointed out by @Justin
    owns     = defaultdict(float)
    owns.update(shares[company])

    # first level of controlled companies to look at
    add_control = set(k for k,v in owns.items() if v > 0.50)

    while add_control:
        # new level of controlled companies to look at next
        _add_control = set()

        for cpy in add_control:
            controls.add(cpy)
            for k,v in shares[cpy].items():
                owns[k] += v
                if owns[k] > 0.5 and k not in controls:
                    _add_control.add(k)
        add_control = _add_control

    return sorted(controls - set([company]))

def main():
    # Data structure: dict of dict of float
    #   shares['A']['B'] = 0.51     means    A owns 51% of B's shares
    shares = defaultdict(lambda: defaultdict(float))

    # Who owns what
    shares['A']['B'] = 0.60
    shares['A']['C'] = 0.55
    shares['A']['D'] = 0.41
    shares['C']['D'] = 0.10
    shares['B']['E'] = 0.20
    shares['C']['E'] = 0.20
    shares['D']['E'] = 0.20

    # See who A controls:
    controlled = find_controlled('A', shares)
    print('A controls {}'.format(','.join(controlled)))

if __name__=="__main__":
    main()