我需要帮助,我觉得我走上了正确的道路,但不知道下一步该做什么。
这是我到目前为止所知道的:
def compareTwoMovies(movie1, movie2):
file = open("actors.txt", "r")
lines = file.readlines()
movies = {}
actors = set()
for lines in file:
actorList = lines.split(",")
movieTitle = actorList[0]
movieActors = actorList[1:]
for movie in file:
if movie not in movies:
movies = movies[movie]
actors.add(movie)
else:
actors.add(movie)读入"actors.txt“文件中的行。对于每一行:将电影和演员分开。对于列出的每个电影:
a)如果电影名称还没有输入到字典中,则将其添加为键,并将演员的集合存储为值。
b)如果字典中存在电影名称,则将演员名称添加到演员集.i.e中。设置为字典中的值。
字典现在已经准备好了。处理函数的输入。
这两个输入键都在你的字典里吗?
a)如果没有,则打印相应的错误消息并退出。
b)如果是,执行三次“搜索”并打印其结果。
发布于 2019-04-26 06:34:43
一些我能看到的问题。
movies = moviesmovie删除了电影的旧值。您正在寻找类似于moviesmovieTitle = actors的东西。
actors = set()需要出现在每一行中。
不需要for movie in file。处理文件中的每一行两次将导致奇怪的问题。
if movie not in movies应使用movieTitle if movieTitle not in movies
您需要遍历movieActors中的每个参与者。
发布于 2019-04-26 07:06:47
def compareTwoMovies(movie1, movie2):
file = open("actors.txt", "r")
lines = file.readlines()# not needed
movies = {}
actors = set()
for lines in file:
actorList = lines.split(",")
movieTitle = actorList[0]
movieActors = actorList[1:]
for movie in file:
if movie not in movies:
movies = movies[movie]
actors.add(movie)
else:
actors.add(movie)
#what is the necessity of two for loop? why not only one?我建议的代码如下
def Init_movies_tree(tree_file_name):
file = open(tree_file_name, 'r')
movies = {}
actors = set()
for line in file:
actorList = line.split(",")
movieTitle = actorList[0]
movieActors = actorList[1:]
movies.setdefault(movieTitle, movieActors)
actors.add(movieTitle)
return movies
def compareTwoMovies1(movie1, movie2, tree, debug=False):
if debug:
print('Movie[1] name:%s, actors:%s\n'%(movie1, tree[movie1]))
print('Movie[2] name:%s, actors:%s\n'%(movie2, tree[movie2]))
#print(f'Movie[1] name:{movie1}, actors:{tree[movie1]})
#print(f'Movie[2] name:{movie2}, actors:{tree[movie2]})
if (movie1 == movies2) and movie1 in tree:
return True
return False
Tree = Init_movies_tree("actors.txt")
v = compareTwoMovies(movie1, movie2, Tree)
print(v)https://stackoverflow.com/questions/55858274
复制相似问题