0

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
  • `def identifier(t): return all(t not in L for L in (keywords, operators, separators))`? – Julien Oct 20 '22 at 00:05
  • Assuming the items in the sequences `keywords`, `separators`, and `operators` are hashable, turn them into `set`s and you can use the [`in` operator](https://stackoverflow.com/questions/8705378/pythons-in-set-operator) to match them. – metatoaster Oct 20 '22 at 00:05
  • Do you want one function that returns true if it finds either a keyword, separator, operator or identifier? If so you could put them in a list and run a function with the any() keyword on them. It will return true if any of those things are found. Let me know if that's what you want: https://www.w3schools.com/python/ref_func_any.asp – answerSeeker Oct 20 '22 at 00:16

2 Answers2

1

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
tdelaney
  • 73,364
  • 6
  • 83
  • 116
0

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))
Dante K
  • 1
  • 1