Create a function map for substring comparison

d = {'a': 'AB', 'b': 'C'}

funcs = ....

funcs['a']('B') --> True
funcs['b']('B') --> False
funcs['b']('C') --> False

Solution 1 - naive solution doesn't work as expected


In [1]:
d = {'a': 'AB', 'b': 'C'}

funcs = {}
for key, value in d.items():
    funcs[key] = lambda v: v in value
    
# True, True, False ?
print(funcs['a']('AB'), funcs['a']('A'), funcs['a']('C'))
# False, True ?
print(funcs['b']('AB'), funcs['b']('C'))


False False True
False True

Changing value changes the function behavior as well


In [2]:
value = "ABCD"
print(funcs['a']('AB'), funcs['a']('A'), funcs['a']('C'), funcs['a']('D'))


True True True True

Solution 2 - function factory using closure


In [3]:
d = {'a': 'AB', 'b': 'C'}

def foo(value):
    def bar(v):
        return v in value
    return bar

funcs = {}
for key, value in d.items():
    funcs[key] = foo(value)
    
# True, True, False ?
print(funcs['a']('AB'), funcs['a']('A'), funcs['a']('C'))
# False, True ?


True True False

In [4]:
d = {'a': 'AB', 'b': 'C'}

def foo(value):
    def bar(v):
        return v in value
    return bar

funcs = {}
for key, value in d.items():
    funcs[key] = foo(value)
    
# True, True, False ?
print(funcs['a']('AB'), funcs['a']('A'), funcs['a']('C'))
# False, True ?
print(funcs['b']('AB'), funcs['b']('C'))


True True False
False True

Changing value doesn't affect the functions


In [5]:
value = "ABCD"
print(funcs['a']('AB'), funcs['a']('A'), funcs['a']('C'), funcs['a']('D'))


True True False False

Solution 3 - partial


In [6]:
from functools import partial

d = {'a': 'AB', 'b': 'C'}

funcs = {}
for key, value in d.items():
    funcs[key] = partial(lambda v, value: v in value, value=value)
    
# True, True, False ?
print(funcs['a']('AB'), funcs['a']('A'), funcs['a']('C'))
# False, True ?
print(funcs['b']('AB'), funcs['b']('C'))


True True False
False True

Changing value


In [7]:
value = "ABCD"
print(funcs['a']('AB'), funcs['a']('A'), funcs['a']('C'), funcs['a']('D'))


True True False False