Python 一次使用多个输入
现在我的程序接受一个输入,并给出一行输出。这个程序基本上使用一个手动安装的python库,名为network-x(它创建和分析图形,并具有许多与图论相关的内置函数) 对于此特定程序,它接受如下所示的输入:Python 一次使用多个输入,python,python-3.x,Python,Python 3.x,现在我的程序接受一个输入,并给出一行输出。这个程序基本上使用一个手动安装的python库,名为network-x(它创建和分析图形,并具有许多与图论相关的内置函数) 对于此特定程序,它接受如下所示的输入: 6 <-- Order of the graph (i.e the graph has 0 to 5 vertices) 1 2 3 <-- vertices going out from 0 2 <-- vertices going out fr
6 <-- Order of the graph (i.e the graph has 0 to 5 vertices)
1 2 3 <-- vertices going out from 0
2 <-- vertices going out from 1
3 5 <-- vertices going out from 2
4 <-- vertices going out from 3
5 <-- vertices going out from 4
<-- vertices going out from 5 (no vertices going out from 5)
6
1 2 3
2
3 5
4
5
6
3 5
2
4
4
0 <-- when the the user inputs a zero, the loop terminates
输入的另一个示例:
6
3 5
2
4
4
和输出:
2
我的程序的源代码是:
import networkx as nx
import sys
def main():
dag = nx.Graph()
order = int(input())
for i in range (order):
dag.add_node(i)
for j in range(order):
seq = [input()]
for vertex in seq:
vertexList = vertex.split()
for element in vertexList:
dag.add_edge(j,int(element))
j+=1
components = nx.number_connected_components(dag)
print (components)
main()
我目前一直在思考如何让程序同时获取这两个输入,并计算两行输出(每行输出每个输入的结果),如下所示:
6 <-- Order of the graph (i.e the graph has 0 to 5 vertices)
1 2 3 <-- vertices going out from 0
2 <-- vertices going out from 1
3 5 <-- vertices going out from 2
4 <-- vertices going out from 3
5 <-- vertices going out from 4
<-- vertices going out from 5 (no vertices going out from 5)
6
1 2 3
2
3 5
4
5
6
3 5
2
4
4
0 <-- when the the user inputs a zero, the loop terminates
任何帮助都将不胜感激。
注意:如果要安装network-x库,请访问network-x的github网站:
只需使用循环并将每个结果保存在
列表中即可:
def main():
result = []
while 1:
dag = nx.Graph()
order = int(input())
if not order: # check if it's 0
break # end the loop
for i in range (order):
dag.add_node(i)
for j in range(order):
vertexList = input().split() # no need to put this single string into a list
for element in vertexList:
dag.add_edge(j,int(element))
result.append(nx.number_connected_components(dag))
print (result)
我已经删除了不必要的[input()]
,它生成了一个元素列表
,可以循环使用。访问单个对象不需要进行循环。我还用j
删除了循环末尾的j+=1
,因为所做的一切就是在它从范围
对象获取下一个值之前重新分配一个新值。它什么也没做。将main
函数放在一个循环中,将组件存储在一个列表中,当顺序
等于0
时退出,并输出组件
列表。