2016-08-24 208 views
0

我需要帮助减少下面的代码的圈复杂度:的Python:降低圈复杂度

def avg_title_vec(record, lookup): 
    avg_vec = [] 
    word_vectors = [] 
    for tag in record['all_titles']: 
     titles = clean_token(tag).split() 
     for word in titles: 
      if word in lookup.value: 
       word_vectors.append(lookup.value[word]) 
    if len(word_vectors): 
     avg_vec = [ 
      float(val) for val in numpy.mean(
       numpy.array(word_vectors), 
       axis=0)] 

    output = (record['id'], 
       ','.join([str(a) for a in avg_vec])) 
    return output 

例输入:

record ={'all_titles': ['hello world', 'hi world', 'bye world']} 

lookup.value = {'hello': [0.1, 0.2], 'world': [0.2, 0.3], 'bye': [0.9, -0.1]} 

def clean_token(input_string): 
    return input_string.replace("-", " ").replace("/", " ").replace(
    ":", " ").replace(",", " ").replace(";", " ").replace(
    ".", " ").replace("(", " ").replace(")", " ").lower() 

所以一切都存在于lookup.value的话,我正在考虑它们的矢量形式的平均值。

+1

你介意解释代码试图在第一个地方做什么? –

+0

增加了一些更多的细节 – futurenext110

+0

我试着从一开始就编码这个自己,我结束了相同的代码:) –

回答

0

它可能不算真正的答案,因为最终圈复杂度不会降低。

这个变种稍微短一些,但是我看不出它可以被推广到的任何方式。看起来你需要那些if

def avg_title_vec(record, lookup): 
    word_vectors = [lookup.value[word] for tag in record['all_titles'] 
        for word in clean_token(tag).split() if word in lookup.value] 
    if not word_vectors: 
     return (record['id'], None) 
    avg_vec = [float(val) for val in numpy.mean(
       numpy.array(word_vectors), 
       axis=0)] 

    output = (record['id'], 
       ','.join([str(a) for a in avg_vec])) 
    return output 

根据this,你的CC是6,这已经很好了。你可以通过使用帮助功能减少你的功能CC,如

def get_tags(record): 
    return [tag for tag in record['all_titles']] 

def sanitize_and_split_tags(tags): 
    return [word for tag in tags for word in 
      re.sub(r'[\-/:,;\.()]', ' ', tag).lower().split()] 

def get_vectors_words(words): 
    return [lookup.value[word] for word in words if word in lookup.value] 

它会降低平均CC,但整体CC将保持不变或增加。我看不到你如何摆脱那些if检查单词是否在lookup.value或检查我们是否有任何媒介可以使用。