Logic errors when searching for a repeated element in a loop

More than once I seem to have done this mistake. The situation is like this. I was inserting some elements into a database at irregular intervals. I needed to know that I dont insert duplicate symbols. So I was wrote a small method to check this. The below code is not exactly the same method, but its enough to explain the errors:
def rejected_symbols(symbol):
rejected_list = [‘TRUE’,’CAST’,’ELSE’,’LONG’, ‘LOOP’,’TO’]
for val in rejected_list:
if val == symbol:
{
return 0
else:
return 1
}
The above is a python snippet but I put the braces for clarity. Now what happens is we dont loop through the entire list. As soon as we see a single element doesnt match we return OR vice versa. Hence we are returning the incorrect value.
The correct logic would be
def rejected_symbols(symbol):
rejected_list = [‘TRUE’,’CAST’,’ELSE’,’LONG’, ‘LOOP’,’TO’]
for val in rejected_list:
{
if val == symbol:
{
return 0
}
}
to return at the end of the looping of the list, in this way we dont return when we find a true value.

In

Leave a Reply

Your email address will not be published. Required fields are marked *