我几天来一直在研究用Python类编程简介这个问题。目标是创建一个程序,从用户输入的单词列表中生成随机电影标题。输出应该如下所示:
Please enter a list of words: ["Space", "Show", "Adventure", "Story",
"Love", "Wild", "Life"]
Please enter a number of movies you'd like to generate: 3
输出:
欢迎来到Randoplex!目前正在播放的电影是:
冒险生活空间
展示爱情故事
野生太空生活
我已经能够生成随机标题,但无论如何都无法根据用户输入的数字生成不同的标题。这是我得到的最接近的:
import random
def random_movies(word_list = eval(input("Please enter a list of words:"))):
for word in word_list:
titles = ' '.join(random.choice(word_list) for i in range(3))
return titles
def repeat():
titles = random_movies()
movie_num = eval(input("Please enter the number of movies you'd like to generate:"))
for i in range(movie_num):
random_movies()
print(titles)
titles1 = repeat()
print("Welcome to Randoplex! Currently playing movies are:")
print()
print(titles1)
这允许我为用户输入的值movie_num
打印相同的随机标题。但是,我无法弄清楚如何创建多个不同的随机电影片头。我尝试过以多种不同的方式使用range()
功能,并在互联网上寻求建议。我真的不知道还有什么可以尝试,任何帮助将不胜感激。值得一提的是,我的班级非常基础,我们还没有被引入"而#34;循环,我不认为我被允许使用它们因此。先感谢您。
答案 0 :(得分:0)
您的功能正常工作,但在您的for循环中,您打印的电影标题,您忘记将变量重新分配给新生成的电影标题。生成了不同的标题,但只打印了第一个标题。
import random
def random_movie(word_list = eval(input("Please enter a list of words:"))):
for word in word_list:
title = ' '.join(random.choice(word_list) for i in range(3))
return title
def repeat():
movie_num = eval(input("Please enter the number of movies you'd like to generate:"))
for i in range(movie_num):
title = random_movie()
print(title)
print("Welcome to Randoplex! Currently playing movies are: ")
print()
repeat()
答案 1 :(得分:0)
这是否符合您的要求?
import random
def random_movies(word_list):
for word in word_list:
titles = ' '.join(random.choice(word_list.split()) for i in range(3))
return titles
word_list = input("Please enter a list of words:")
movie_num = int(input("Please enter the number of movies you'd like to generate:"))
print("Welcome to Randoplex! Currently playing movies are:")
for i in range(movie_num):
print(random_movies(word_list))
答案 2 :(得分:-1)
获得类似结果的另一种方式。
import itertools
import random
noofmovies = 3
movies = ["Space", "Show", "Adventure", "Story", "Love", "Wild", "Life"]
newmovies = []
def random_movie(movies):
for r in range(2,len(movies)):
for elem in itertools.combinations(movies, r):
newmovies.append(" ".join(elem))
def repeat():
random.shuffle(newmovies)
for elem in newmovies[0:noofmovies]:
print (elem)
print("Welcome to Randoplex! Currently playing movies are: ")
random_movie(movies)
repeat()
输出:
Show Adventure Story Wild Life
Story Wild Life
Show Adventure Story Love Wild Life
如果您只想连接3个电影名称,请删除范围内的r(2,len(电影)):循环并将硬编码转换为3