You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何优化简易Python电影推荐程序的运行效率?

Python电影推荐程序优化方案

一、核心问题拆解

当前代码的重复点在于每个电影类型的长度筛选逻辑完全一致,仅类型字段不同。这种重复不仅增加维护成本,还容易出现修改遗漏的问题。

二、具体优化步骤

1. 提取通用筛选函数

把重复的筛选逻辑封装成独立函数,接收目标类型和长度条件作为参数,彻底消除重复代码:

def filter_movies(target_genre, length_condition):
    filtered = []
    for movie in movies:
        # 先匹配类型(忽略大小写)
        if movie[1].lower() != target_genre.lower():
            continue
        # 根据长度条件筛选
        runtime = movie[2]
        if length_condition == "1.5 - 2":
            if 1.5 <= runtime <= 2:
                filtered.append(movie)
        elif length_condition == "2 - 2.5":
            if 2 < runtime <= 2.5:
                filtered.append(movie)
        elif length_condition == "2.5+":
            if runtime > 2.5:
                filtered.append(movie)
        elif length_condition == "No preference":
            filtered.append(movie)
    return filtered

2. 简化主流程逻辑

主函数只需处理用户输入,调用通用函数即可,无需为每个类型写重复分支:

movies = [
    ["Wedding Crashers", "Comedy", 2],
    ["Horrible Bosses", "Comedy", 1.75],
    ["Dodgeball", "Comedy", 1.5],
    ["Superbad", "Comedy", 2],
    ["Dumb and Dumber", "Comedy", 1.75],
    ["Shawshank Redemption", "Drama", 2.33],
    ["Goodwill Hunting", "Drama", 2],
    ["The Departed", "Drama", 2.5],
    ["Whiplash", "Drama", 1.75],
    ["Manchester by the Sea", "Drama", 2.25],
    ["Die Hard", "Action", 2.25],
    ["John Wick", "Action", 1.75],
    ["Terminator", "Action", 1.75],
    ["First Blood", "Action", 1.5],
    ["Predator", "Action", 1.75],
    ["The Conjuring", "Horror", 2],
    ["Sinister", "Horror", 2],
    ["Insidious", "Horror", 2]
]

def filter_movies(target_genre, length_condition):
    filtered = []
    for movie in movies:
        if movie[1].lower() != target_genre.lower():
            continue
        runtime = movie[2]
        if length_condition == "1.5 - 2":
            if 1.5 <= runtime <= 2:
                filtered.append(movie)
        elif length_condition == "2 - 2.5":
            if 2 < runtime <= 2.5:
                filtered.append(movie)
        elif length_condition == "2.5+":
            if runtime > 2.5:
                filtered.append(movie)
        elif length_condition == "No preference":
            filtered.append(movie)
    return filtered

def program():
    print("欢迎来到电影推荐程序!")
    print("我们将帮你找到合适的电影!")
    start = input("是否开始?y/n ")
    if start.lower() == "y":
        genre = input("你感兴趣的类型是?可选:Comedy, Drama, Action, Horror - 请选择一个: ")
        length = input("你对电影时长有偏好吗?可选:1.5 - 2, 2 - 2.5, 2.5+, No preference - 请选择一个: ")
        # 调用通用函数筛选并输出结果
        recommended = filter_movies(genre, length)
        print("推荐电影:")
        for movie in recommended:
            print(movie)

program()

3. 进阶优化:提升搜索效率

如果后续电影数据量增大,可通过以下方式优化:

  • 按类型预分组:提前将电影按类型归类到字典中,避免每次筛选都遍历全部电影:
    # 预生成类型分组字典
    genre_groups = {}
    for movie in movies:
        genre = movie[1]
        if genre not in genre_groups:
            genre_groups[genre] = []
        genre_groups[genre].append(movie)
    
    之后筛选时,直接从对应类型的子列表中处理,减少遍历次数。
  • 排序+二分查找:将每个类型的电影按时长排序,使用bisect模块快速定位时长范围的边界,适合大数据量场景。

4. 可选:添加输入容错

增加输入验证,避免用户输入无效选项导致程序异常:

valid_genres = {"comedy", "drama", "action", "horror"}
while genre.lower() not in valid_genres:
    genre = input("输入类型无效,请重新输入可选类型:Comedy, Drama, Action, Horror - ")

valid_lengths = {"1.5 - 2", "2 - 2.5", "2.5+", "No preference"}
while length not in valid_lengths:
    length = input("输入时长选项无效,请重新输入:1.5 - 2, 2 - 2.5, 2.5+, No preference - ")

三、搜索算法应用说明

结合你的需求,不同搜索算法的适用场景:

  • 线性搜索:当前代码的实现方式,适合小数据量,逻辑简单直接。
  • 分块搜索/二分查找:当数据量较大时,先将同类型电影按时长排序,再用二分查找快速定位符合时长范围的电影,能大幅提升搜索效率。

内容的提问来源于stack exchange,提问作者Paulie Walnuts

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 11:40:04