如何构建Python代码:函数,类,模块?

时间:2014-11-19 04:49:00

标签: python networkx

这是一个关于如何更好地将Python代码组织成函数/类和模块的问题。如果您能解释一下组织工作的最佳方式,我将非常感激。

代码可分为两部分:第1部分构建基于Networkx(DiGraph)的树,Part2对此树的节点进行一些计算,通过其节点递归工作并输出数字。

代码的简化版本:

a1 = 200; a2=250; n=50                       #Constants, User inputs
constantes =['x','y','z']                    #Constants calculated from User input
G=nx.DiGraph()                               #I initiate the graph
for step in range(0,n+1):
    if not current_step_nodes:
        current_step_nodes = ['a']
        G.add_nodes_from(current_step_nodes)
    else:
        for i in current_step_nodes:
            a=[i]
            for j in constantes:
                a.append(''.join(sorted(i + j)))
            G.add_edges_from(_tree_edges(a,3))
            a=[]
    current_step_nodes = [w for w in G.nodes() if len(w) == step]

所以这构建了一个看起来像的树G:

 For n=2: a->ax, a->ay, a->az

下一步:我将属性's1'和's2'添加到G的每个节点。

for ns1 in G.nodes():
    G.node[ns1]['s1']=products1     #products1 are numbers calculated in the code
    G.node[ns1]['s2']=products2

-----这结束了树,我希望我可以保存它,不要再触摸它。

第2部分:添加atribure'值'并从叶子递归工作:

for leafs in set(w for w in G.nodes() if len(w) == n):
    G.node[leafs]['value']=max(s1*G.node[leafs]['s1']-s2*G.node[leafs]['s2'],0)
for i in reversed(xrange(n)):
    nodes_in_i = [w for w in  G.nodes() if len(w) == i]
    for node in nodes_in_i:
        for succ in G.successors(node):
            G.node[node]['value']=G.node[node]['value']+G.node[succ]['value']

最终我对'a'的'价值'的价值感兴趣。目前我将此代码作为名为arbol(n)的大型函数的一部分,所以我只是:

return G.node['a']['value']

----我现在想看看当n增加时这个'价值'是如何变化的:

def main(): 
    for n in xrange(8):
        print arbol(n)

----现在的事情是,例如我想用这个树做更多的东西G喜欢添加更多属性并做其他计算,比如看看G.node ['a'] ['value']如果改变了用户输入更改。

理想情况下,我希望将其分成几个文件,例如:arbol.py,value.py,value_when_n_changes.py等。

这是我认为应该组织代码的方式。但我不知道如何构造它并对其进行编码(即该图可以是一个类吗?G可以是这个类的一个实例吗?我可以使用函数更改/添加该图G的属性吗?)。

感谢您的建议!我是Python的新手!

0 个答案:

没有答案
相关问题