【问题标题】:Python: reducing cyclomatic complexityPython:降低圈复杂度
【发布时间】:2016-08-24 11:55:12
【问题描述】:

我需要帮助来降低以下代码的圈复杂度:

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 中存在的所有单词,我正在取它们的向量形式的平均值。

【问题讨论】:

  • 你介意解释一下代码首先要做什么吗?
  • 添加了更多细节
  • 我从一开始就尝试自己编写代码,但最终得到了相同的代码:)

标签: python cyclomatic-complexity


【解决方案1】:

这可能算不上真正的正确答案,因为最终圈复杂度并没有降低。

这个变种有点短,但我看不出有什么方法可以概括它。看来你需要那些ifs。

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 将保持不变或增加。我不知道您如何摆脱那些 ifs 检查单词是否在 lookup.value 或检查我们是否有任何向量可以使用。

【讨论】:

    猜你喜欢
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    相关资源
    最近更新 更多