Search code examples
pythonarraysoptimizationmatchingboolean-operations

Optimizing Several True/False Functions in Python


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

Solution

  • 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