好的,所以我现在已经尝试了大约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。
让我举个例子,让我说我有这个词:
{0: [], 1: [], 2: [], 3: [], 4: []}
屏幕录制示例:
答案 0 :(得分:0)
您的验证仅运行 while checkInt(vertex) is False:
- 如果它是第一次有效的整数,您永远不会检查其余的。并不是graf.checkVertex(vertex)
不起作用;它永远不会被称为。相反,尝试:
def readVertex(msg, graf, invalid_input):
"""
msg - string message
graf - Graph() class instance initialised somewhere
invalid_input - string error message
"""
while True:
vertex = raw_input(msg)
if checkInt(vertex) and graf.checkVertex(int(vertex)):
return int(vertex)
print invalid_input
或
def readVertex(msg, graf, invalid_input):
"""
msg - string message
graf - Graph() class instance initialised somewhere
invalid_input - string error message
"""
while True:
try:
vertex = int(raw_input(msg))
except ValueError:
print invalid_input
else:
if graf.checkVertex(vertex):
return vertex
print invalid_input