OK, so I've been trying this for about 2 hours now and I can't seem to figure it out. I think I tried almost every possible algorithm combination and it still isn't working. Here it goes:
I'm trying to validate keyboard input in Python based on two condition (ordered by priority):
- Check if input is integer
- Check if input is vertex (class method for checking if the number given can be found as a key in a dictionary)
Here's the code:
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)
The problem that I'm getting is that the first condition works, so if I input a letter it will print an error, but if I input a number and that number isn't in the keys of the dictionary it will still return it.
So graf.checkVertex(vertex) always returns True in the above code even though I know for a fact that it works because I've tried the function with the same input in the shell and it returned False.
Let me give you an example, let's say I have this dict:
{0: [], 1: [], 2: [], 3: [], 4: []}
Screen recording of example: