Aspect11
Aspect11

Reputation: 328

Input a string with a comparison operator and perform the comparison on an array index

So here's my code so far:

# Function to search for possible matches for words: and chapters:
def intSearch(term, row, index):
    """
    Index of 6: Word search
    Index of 7: Chapter search
    """
    rowValue = row[index]
    if True:
        return True
    return False

The 'if True' is just temporary. So what I want is for the term input to be a comparison operator then a integer, for example '>=334'. Then this string can be broken down and compared to the specific index of the row which I can use row[index] for. If this comparison is correct, it'll return True and if not, it'll return False. The comparison should work for basically all operators including: ==, !=, >, <, <=, >= and for a range.

So the comparison will basically look like:

if row[index] >= term:

Where row[index] is array integer, >= is the comparison operator and term is the number you want to compare on.

I could use alot of if and else statements although I'm not sure how efficient that would be.

Hope I made this clear. Thanks!

Upvotes: 1

Views: 432

Answers (1)

rhurwitz
rhurwitz

Reputation: 2747

Two very useful concepts for this type of problem, the standard operator library and a standard dictionary.

Example:

import operator as op

op_map = {
    "==": op.eq,
    "!=": op.ne,
    ">": op.gt,
    "<": op.lt,
    "<=": op.le,
    ">=": op.ge,
}

x = 10
y = 0

for op_str in op_map:
    print(f"{x} {op_str} {y}: {op_map[op_str](x, y)}")

Output:

10 == 0: False
10 != 0: True
10 > 0: True
10 < 0: False
10 <= 0: False
10 >= 0: True

Upvotes: 3

Related Questions