2015-11-06 85 views
1

我正在处理一段代码,需要验证两个用户是否在几个不同的标准下“匹配”。如果有帮助的话,可以把它看作是一个约会应用程序,我们试图根据年龄,性取向,种族偏好等来匹配人。以下是一个有3个条件的例子,每个条件都是一个函数。什么是验证多种复杂条件的良好模式?

def is_match(row): 
    return True \ 
     and ethnicity(user_a, user_b) \ 
     and sexual_orientation(user_a, user_b) \ 
     and age(user_a, user_b) \ 

现在,让我们说,我想增加对邻近另一个条件,我只想把它添加到功能:

def is_match(row): 
    return True \ 
     and ethnicity(user_a, user_b) \ 
     and sexual_orientation(user_a, user_b) \ 
     and age(user_a, user_b) \ 
     and proximity(user_a, user_b) 

当然,这是一个小的应用是可行的,但我可以想象一下,其他同事可能想要检查代码并将自己的条件传递给它的点,而这看起来不够抽象。我知道这里必须有一个模式可以遵循。我应该像数组一样传递每个函数吗?你会如何推荐这样做?我正在使用Python,但您可以使用任何您想要演示模式的语言。

+0

有你打得四处['任何()'和'所有()'](https://docs.python.org/2/library/functions.html#all)? – Kevin

+0

是的,我以前使用过这些。所以这个想法是传递一个函数列表和两个用户对象,并且只对它们执行任何()或全部()操作?是的,这可能是我现在拥有的改进。谢谢。 –

回答

1
def is_match(list_of_functions, user_a, user_b): 
    return all([cur_fun(user_a, user_b) for cur_fun in list_of_functions]) 

编辑:

以下的变体是更有效,因为它短路瞬间就击中一个非真实价值,而不是必然评估所有的功能:

def is_match(list_of_functions, user_a, user_b): 
    for cur_fun in list_of_functions 
     if not cur_fun(user_a, user_b): 
      return False 
    return True 
1

我认为集合对于这样的任务是很好的,因为它比验证更具有比较性。我给你举例:

user_a = { 
    'ethnicity': 1, 
    'sexual_orientation': 'straight', 
    'age': 37, 
} 

user_b = { 
    'ethnicity': 2, 
    'sexual_orientation': 'straight', 
    'age': 34, 
} 

differences = set(user_a.items())^set(user_b.items()) # s.symmetric_difference(t) 
commons = set(user_a.items()) & set(user_b.items()) # s.intersection(t) 

print({'differences': differences, 'commons': commons}) 

输出:

{'differences': {('ethnicity', 2), ('ethnicity', 1), ('age', 37), ('age', 34)}, 'commons': {('sexual_orientation', 'straight')}} 

所以你可以只加载两个用户的数据类型的字典和比较。