用Python编程:已知有演员8人,导演4人,电影9部,现随机给每部电影分配4个演员和一个导演,现查找关系最好的两个演员以及他们共同参演的电影和电影的导演,并输出。这里假设,如果某两个演员共同参演电影的数量最多,那么这二人关系最好。运行结果示例: 电影1: [导演1,演员1,演员2,演员3,演员4] 电影2: [导演3,演员4,演员3,演员1,演员5] …… 关系最好的两个演员是:(演员1,演员2) 共同参演的电影和导演是:(电影1,导演1)
时间: 2023-04-02 20:01:42 浏览: 96
我可以回答这个问题。以下是Python代码实现:
import random
actors = ['演员1', '演员2', '演员3', '演员4', '演员5', '演员6', '演员7', '演员8']
directors = ['导演1', '导演2', '导演3', '导演4']
movies = ['电影1', '电影2', '电影3', '电影4', '电影5', '电影6', '电影7', '电影8', '电影9']
movie_cast = {}
for movie in movies:
movie_cast[movie] = [random.choice(directors)]
for i in range(4):
actor = random.choice(actors)
while actor in movie_cast[movie]:
actor = random.choice(actors)
movie_cast[movie].append(actor)
actor_movies = {}
for actor in actors:
actor_movies[actor] = []
for movie in movie_cast:
if actor in movie_cast[movie]:
actor_movies[actor].append(movie)
best_actors = ('', '')
best_movies = []
best_directors = []
for i in range(len(actors)):
for j in range(i+1, len(actors)):
common_movies = set(actor_movies[actors[i]]) & set(actor_movies[actors[j]])
if len(common_movies) > len(set(best_movies)):
best_actors = (actors[i], actors[j])
best_movies = list(common_movies)
best_directors = [movie_cast[movie][] for movie in best_movies]
print('关系最好的两个演员是:({},{})'.format(best_actors[], best_actors[1]))
print('共同参演的电影和导演是:')
for i in range(len(best_movies)):
print('{}: [{}, {}, {}, {}, {}]'.format(best_movies[i], best_directors[i],
best_actors[], best_actors[1],
random.choice(actors), random.choice(actors)))
阅读全文