Home > Software design >  Is there a better way to look if a string is contained in a different lists of strings?
Is there a better way to look if a string is contained in a different lists of strings?

Time:10-20

I have a string called "block", and I want to check in which list it is contained. It works for me as below, but I was wondering if there is a better way (maybe a mapper or dict key\value or something similar). This is what I have:

def get_block_container(block: str) -> str:

    if block in ['sss', 'srs']:
        return 'prime'
    if block in ['aaa', 'aba']:
        return 'general'
    if block in ['kkk', 'klk']:
        return 'alpha'
    if block in ['zyz', 'zzz']:
        return 'beta'
    return ''

Is there a simpler way to do it? as the list may go longer with time.

Thanks!

CodePudding user response:

Your current approach has a complexity of O(n*m) (where n is the number of branches and m the length of the longest list) I'd use a dictionary which will allow for a O(1) lookup:

def get_block_container(block: str) -> str:
    return {
        'sss': 'prime',
        'srs': 'prime',
        'aaa': 'general',
        'aba': 'general',
        'kkk': 'alpha',
        'klk': 'alpha',
        'zyz': 'beta',
        'zzz': 'beta'
    }.get(block, '')

This can be improved more by defining the dictionary as a const outside of the function (so it doesn't need to be created every time the function is called) and by using consts/enum for the values so there is less repetition, for example:

...

BLOCK_CONTAINER_MAPPING = {
        'sss': 'prime',
        'srs': 'prime',
        'aaa': 'general',
        'aba': 'general',
        'kkk': 'alpha',
        'klk': 'alpha',
        'zyz': 'beta',
        'zzz': 'beta'
    }

...

def get_block_container(block: str) -> str:
    return BLOCK_CONTAINER_MAPPING.get(block, '')

CodePudding user response:

you can define a dictionary that has the mapping of strings such as

example_dict = {
"sss" : "prime" # So the value of sss will be prime
"srs" : "prime"  # So the value of srs will be prime
"aaa" : "general"  # So the value of aaa will be general
"aba" : "general"  # So the value of aba will be general
#...
}

then you can use dictionaries get() method to find out the value of block.

CodePudding user response:

You can store the return values in a dict as keys and return them like this:

def get_block_container(block: str) -> str:

    dict_list = {"prime": ['sss', 'srs'], "general": ['aaa', 'aba'], "alpha": ['zyz', 'zzz']}

    for key in dict_list:
        if block in dict_list[key]
            return key
  • Related