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
3
  • def identifier(t): return all(t not in L for L in (keywords, operators, separators))? Commented Oct 20, 2022 at 0:05
  • Assuming the items in the sequences keywords, separators, and operators are hashable, turn them into sets and you can use the in operator to match them. Commented Oct 20, 2022 at 0: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: w3schools.com/python/ref_func_any.asp Commented Oct 20, 2022 at 0:16

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.