题目:定义三个函数,
-
search_by_name(filename: str, word: str),返回菜单中的所有菜肴名字,菜肴的名字必须包含word。
具体如图:
-
search_by_time(filename: str, prep_time: int),返回准备时间小于prep_time的所有菜肴名字。
具体如图:
-
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



