栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python | 菜单,实现查找功能

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python | 菜单,实现查找功能

题目:定义三个函数,

  1. search_by_name(filename: str, word: str),返回菜单中的所有菜肴名字,菜肴的名字必须包含word。

    具体如图:

  2. search_by_time(filename: str, prep_time: int),返回准备时间小于prep_time的所有菜肴名字。

    具体如图:

  3. search_by_ingredient(filename: str, ingredient: str),返回菜肴需要的食材中有ingredient的所有菜肴名字和准备时间。

    具体如图:


代码如下: 若有改进之处,求指点~

# Write your solution here
def read_file(filename:str):
    list = []
    dish_locate = [0]
    with open(filename) as new_file:
        for line in new_file:
            line = line.strip()
            if line != '':
                list.append(line)
            else:
                l = len(list)
                dish_locate.append(l)
    
    return [list,dish_locate]  
	# list存储菜单详情,dish_locate存储的是每一个菜肴名字的位置。

def search_by_name(filename: str, word:str):
    dish_locate = read_file(filename)[1]
    list = read_file(filename)[0]
    search_word = []
    for num in dish_locate:
        if word in list[num].lower():  # 如果word在菜肴名字中,并且确保菜肴名字全部为小写
            search_word.append(list[num])
    return search_word

def search_by_time(filename: str, prep_time: int):
    time = []  # 存储着准备时间小于prep_time的菜肴,以一句话形式表示
    dish_locate = read_file(filename)[1]
    list = read_file(filename)[0]

    for num in dish_locate:
        if prep_time >= int(list[num+1]):
            a = list[num]+", preparation time "+list[num+1]+" min"
            time.append(a)
    return time

def search_by_ingredient(filename: str, ingredient: str):
    dish_locate = read_file(filename)[1]
    list = read_file(filename)[0]
    dish_locate.append(len(list))  # 添加一个list的长度数。

    i = 0
    j = 1
    search_in = []  # 存储全部有ingredient的菜肴位置
    ingre = []  # 存储含有ingredient的全部位置
    while i < len(list):
        if ingredient == list[i]:  
            ingre.append(i)
        i+=1
    for ingre_num in ingre:
        while j < len(dish_locate):
            if ingre_num < dish_locate[j]:  # ingredient的位置小于第二个菜肴开始的位置,所以上面给dish_locate添加了一个list长度的目的就是为了确保ingredient在最后一个菜肴也能被找到。
                search_in.append(dish_locate[j-1])
                break
            j+=1

    output = []
    for num in search_in:
            a = list[num] + ", preparation time " + list[num + 1] + " min"
            output.append(a)

    return output
                    


if __name__ == "__main__":
    found_recipes = search_by_ingredient("recipes1.txt", "eggs")
    for recipe in found_recipes:
        print(recipe)

题目来源:Helsinki,programming, part 6

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/979878.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号