好吧,我已经试了2个小时了,但我好像搞不懂。我想我几乎尝试了所有可能的算法组合,但仍然不起作用。接下来是:
我尝试基于两个条件(按优先级排序)验证Python中的键盘输入:
代码如下: 在
def checkVertex(self, x):
ok = 0
for key in self.__inv:
if key == x:
ok += 1
break
for key in self.__outv:
if key == x:
ok += 1
break
if ok == 2:
return True
return False
def checkInt(number):
if number.isdigit() is False:
return False
return True
def readVertex(msg, graf): <-- this is the issue
"""
msg - string message
graf - Graph() class instance initialised somewhere
invalid_input - string error message
"""
vertex = raw_input(msg)
while checkInt(vertex) is False:
print invalid_input
vertex = raw_input(msg)
if checkInt(vertex) is True:
vertex = int(vertex)
if graf.checkVertex(vertex) is True: <-- this bloody line is not working right
return vertex
else:
continue
return int(vertex)
source = readVertex("Give source vertex (by number): ", G)
dest = readVertex("Give destination vertex (by number): ", G)
cost = int(raw_input("Give cost: "))
print G.addEdge(source, dest, cost)
我遇到的问题是第一个条件起作用,所以如果我输入一个字母,它将输出一个错误,但是如果我输入一个数字,而这个数字不在字典的键中,它仍然会返回它。在
所以graf.checkVertex(vertex)在上面的代码中总是返回True,尽管我知道它是有效的,因为我在shell中用相同的输入尝试了这个函数,但它返回了False。在
我给你举个例子,假设我有这样一句话:
^{pr2}$示例的屏幕录制:
您的验证只运行
while checkInt(vertex) is False:
-如果第一次验证是有效的整数,则永远不会检查其余的。并不是graf.checkVertex(vertex)
不起作用;它从未被调用过。相反,请尝试:或者
^{pr2}$相关问题 更多 >
编程相关推荐