Home > other >  Optimizing Several True/False Functions in Python
Optimizing Several True/False Functions in Python

Time:10-20

While the provided code I created works, it is non-scalable and slow. I need a way to determine if a token (t) is the same as any element in several arrays. However, it cannot match more than one array, as one list might supersede the other. Is there any way to succinctly and quickly program this in python other than using tons of individual functions?

def keyword(t):
    for n in keywords:
        if t == n: 
            return True
            break
    else:
        return False
def separator(t):
    for n in separators:
        if t == n: 
            return True
            break
    else:
        return False
def operator(t):
    for n in operators:
        if t == n: 
            return True
            break
    else:
        return False 
def identifier(t):
    if keyword(t) is False and operator(t) is False and separator(t) is False:
        return True
    else:
        return False

CodePudding user response:

The keyword function is just n in keywords - a test of containment. This is generally faster using a set. So, combine call of your categories and test from there.

identifiers = {(*keywords, *separators, *operators)}

def identifier(t):
    return t in identifiers

CodePudding user response:

the way I find that you could do what you ask is simply using a function that requires 2 parameters and creating an array that contains all the arrays you need to compare, making a function that cycles through each of the arrays trying to find a match.

I do it this way:

keywords = ["Hi", "World"]
separators = ["Hola", "Mundo"]
operators = ["My", "name"]
lists = [keywords, separators, operators]
t = "F"


def comparator(token, arrays):
    for array in arrays:
        for item in array:
            if token == item:
                return False
        else:
            return True


print(comparator(token=t, arrays=lists))
  • Related