Repeating for loop within a function Python 3 - python

I have been working on this problem for an Intro to Programming with Python class for days now. The goal is to create a program that generates random movie titles from a list of user-inputed words. The output should look something like this:
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
Output:
Welcome to Randoplex! Currently playing movies are:
Adventure Life Space
Show Love Story
Wild Space Life
I have been able to generate random titles, but cannot find anyway to generate different titles based on the user-inputed number. This is the closest I have gotten:
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)
This allows me to print the same randomized title for the value movie_num that the user enters. But, I just cannot figure out how to create multiple different randomized movie titles. I have tried using the range() function in many different ways, and have looked all over the internet for advice. I truly don't know what else to try at this point, any help would be greatly appreciated. It is important to mention that my class is very elementary, we haven't been introduced to "while" loops yet and I don't think I am allowed to use them because of that. Thank you in advance.

Does this do what you're looking for?
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))

Your functions are working correctly however in your for loop where you print the movie titles you forgot to reassign your variable to the newly generated movie title. Your different titles are generated but you print only the first one.
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()

another way to achieve similar result.
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()
output:
Show Adventure Story Wild Life
Story Wild Life
Show Adventure Story Love Wild Life
In case you want only 3 movie names to be joined always, remove for r in range(2,len(movies)): loop and hardcode r to 3

Related

How do I ask for a set list in Python, ask for a number (x), remove x number of inputs, and re-list those?

I am new to Python, and I am currently learning about lists. This is the question that I am trying to solve:
Your favourite band is in town, and tickets are selling fast! Alas,
you were too late to snag one, so you put your name in the waitlist,
in case any extra tickets are released.
Write a program to manage the waitlist for the concert.
Your program should read in a list of the names in the waitlist, and
the number of extra tickets released.
Then, it should announce the names of people who score the extra
tickets.
Here's an example of how your program should work:
People in line: Dave, Lin, Toni, Markhela, Ravi
Number of extra tickets: 3
Tickets released for: Dave, Lin, Toni
Note: The names are separated
by a comma and a space (', ').
If there are no more tickets released, your program should work like
this:
People in line: Mali, Micha, Mary, Monica
Number of extra tickets: 0
Fully Booked!
This band is so popular that there will always be at least as many
people as extra tickets. You won't have to worry about index errors.
I have tried the following, but it always prints the entire list, not just a subset.
ppl = []
sep = ', '
ppl_in_line = input('People in line: ')
ppl.append(ppl_in_line)
x = int(input('Number of extra tickets: '))
if x == 0:
print('Fully Booked!')
else:
y = ppl[:x]
print('Tickets released for: ' + (sep.join(y)))
ppl_in_line is a string. So when you append to ppl, you are appending a single string.
To enter a separated list of ppl on a single line do this:
ppl_in_line = input('People in line: ').split(sep)
You forgot to split your people in line into multiple elements:
ppl_in_line = input('People in line: ')
ppl = ppl_in_line.split(sep)
This is assuming that your input for People in line: is something like
Dave, Lin, Toni, Markhela, Ravi
If you want to use ppl.append, you have to mention them name by name in a loop:
while True:
ppl_in_line = input('People in line: ')
if not ppl_in_line:
break
ppl.append(ppl_in_line)
You can enter the names like
Dave
Lin
Toni
Markhela
Ravi
An empty input will finish the list.

Issue in user input or text file data in sentiment analysis

I am new to Python-NLTK. I have written my code using movie reviews data set.
When I put hard coded sample text for sentiment analysis it is working fine but when I try to take user input or fetch the data from text file it shows alphabet level splitting.
for e.g.
When sample text is hard coded like
["Music was awesome", "Special effects are awesome"]
Then splitting is like a
Review : Music was awesome
Review : Special effects are awesome.
But if I asked for user input or fetch the data from text file then it shows review as;
Review: M
Review: u
Review: S
Review: i
Review: c
Review: .
#For text file Below is my sample code.
t = open ("Sample1.txt", "r")
File_input = (t.read())
for review in File_input:
print ("\nReview:", review)
probdist = classifier.prob_classify(extract_features(review.split()))
pred_sentiment = probdist.max()
print ("Predicted sentiment:", pred_sentiment)
print ("Probability:", round(probdist.prob(pred_sentiment), 5))
#For user input Below is my sample code.
User_input = input("Enter your value: ")
for review in User_input:
print ("\nReview:", review)
probdist = classifier.prob_classify(extract_features(review.split()))
pred_sentiment = probdist.max()
print ("Predicted sentiment:", pred_sentiment)
print ("Probability:", round(probdist.prob(pred_sentiment), 3))
plz guide.
Thanks!
the User_input variable is a string, so iterating over it is iterating over the chars, what you want to do is remove the for loop and treat User_input as a review assuming it holds 1 review, otherwise you could define a separating char between reviews and iterate like so:
for review in User_input.split(sep_char):

Reading a random line from a word doc and printing it

So I have a small project with python.
A random song name and artist are chosen.
The artist and the first letter of each word in the song title are displayed.
The user has two chances to guess the name of the song.
If the user guesses the answer correctly the first time, they score 3 points. If the user guesses
the answer correctly the second time they score 1 point. The game repeats.
The game ends when a player guesses the song name incorrectly the second time.
So far I've created a text document and put a few lines of song titles.
In my code I have used the following:
random_lines = random.choice(open("songs.txt").readlines())
This randomly picks a line in the code and does nothing with it.
I am asking where I go from here. I need to display the first letters of each word on the line. I then need a counter or some sort to add chances. I also need to write something that will check to see if they have it correct and add to a score counter.
OK, now just continue with your plan, it's good. Now you have to get the first letter from each word in line. You can do that with:
res = []
for i in line.split():
res.append(i[0])
There you are, you have the first letter of every word in the list res. Now you need to check if the user entered the title correctly. Maybe the best idea would be to keep everything lower-cased (in your file and in the user input) for easier checking. Now you just have to transform the user input to lower-case. You can do it with:
user_entry = input('Song title:')
if user_entry.lower() == line.lower():
score += 3
else:
user_entry_2 = input('Song title:')
if user_entry_2.lower() == line.lower():
score += 1
else:
print('Game over.')
sys.exit()
You should make this into a function ad call it in a loop until user misses. The function could return the current score which you could print out (in that case you should remove sys.exit() call)
I hope this is clear enough. If not, write the question in the comments :)
Assuming your random choice string contains the data in the format {songname} - {artist}
Then you first need to get the song name and the artist as a separate strings.
Print the first letters and ask for input.
After which you need to compare the strings and do some logic with the points.
points = 0;
while(1):
random_line = 'Song - artist' #change this with your random string
song, artist = random_line.split('-')
print("{0} - {1}".format(song.strip()[:2], artist.strip()[:2]))
for i in range(0,3):
if (i == 2):
print('You died with {} points'.format(points))
exit(0)
elif(random_line.lower() == input('Gues the song: ').lower()):
points += 2 - i
print('correct guess. points: ' + str(points))
break
else:
print('Try again')

How can I test for different strings in a string and act differently upon some of them? Python

What I want to do is look for different strings in a string and act differently upon some of them. Ths is what I have now:
import re
book = raw_input("What book do you want to read from today? ")
keywords = ["Genesis", "genesis", "Gen", "Gen.", "gen", "gen.", "Matthew", "matthew", "Matt", "Matt.", "matt", "matt." ]
if any(keyword in book for keyword in keywords):
print("You chose the book of: " + book)
I plan to change the "print" at the end to another action later on. So basicly if the user inputs the string "Genisis" then it will take action #1 and if the user inputs "Gen." it will also take action #1 as with all the other forms of the string "Genisis" but if the user inputs the string "Matthew" I want it to take action #2 and it should take action #2 with all the other variations of matthew.
I considered something like this:
book = raw_input("What book do you want to read from today? "
if book == "Genesis":
print "Genesis"
but that would require lots of lines for all the variations I have listed of "genesis"
I hope someone can help!
book = raw_input("What book do you want to read from today? ").lower().strip('.')
# keywords = ["Genesis", "genesis", "Gen", "Gen.", "gen", "gen.", "Matthew", "matthew", "Matt", "Matt.", "matt", "matt." ]
if book == 'genesis':
#action1
pass
elif book == 'gen':
#action2
pass
else:
print('not find the book!')
Using slices would still require you to write an if statement, but it would make the reduce the amount of code needed:
if book in keywords[:6]:
print "Genesis"
You can use a for loop and test for the containment of a book in any of a unique set of keywords. Whatever variation the book input takes, str.lower ensures you can find it in a keyword and take action based on the keyword:
actions = {...} # dictionary of functions
keywords = ['genesis', 'matthew', ...]
book = raw_input("What book do you want to read from today? ")
for kw in keywords:
if book.lower() in kw:
actions[kw]() # take action!
break # stop iteration

My append command won't work (Python)

I am a new programmer and I am teaching myself using Sams Teach Yourself Python in 24 Hours, and one of the excersises told me to rewrite a piece of code that allows the clerk to work out orders at a restraunt and it told me change it so to include the price, so I did, but I want to use the user's input of the price and to put it into a list to sum it up and print out the total. However, it doesn't work. What should I do?
Here is the code:
breakfast_special = "Texas Omelet"
breakfast_notes = "Contains brisket, horseradish cheddar"
lunch_special = "Greek patty melt"
lunch_notes = "Like the regular onem but with tzatziki sauce"
dinner_special = "Buffalo Steak"
dinner_notes = "Top loin with hot sauce and blue cheese, NOT BUFFALO MEAT"
while True:
meal_time = raw_input("Which mealtime do you want? [breakfast, lunch, dinner, q to quit]")
if meal_time == "q":
break
price = raw_input("Price: $")
price.append(price)
total_price = sum.price
if meal_time == "breakfast":
print "Specials for {} :".format(meal_time)
print breakfast_special
print breakfast_notes
elif meal_time == "lunch":
print "Specials for {} :".format(meal_time)
print lunch_special
print lunch_notes
elif meal_time == "dinner":
print "Specials for {} :".format(meal_time)
print dinner_special
print dinner_notes
else:
print "Sorry, but {} isn't a valid choice".format(meal_time)
print "Goodbye!"
print "Price: ${}".format(total_price)
raw_input() takes a string input.
So when you try to do price = raw_input() , the user input is saved as string type to your variable 'price'. To convert that value to int/float, you can do int(price) or float(price)
Note: You have to make sure the user_input is actually a number. If the variable 'price' has characters, converting it to int/float will result in a ValueError
To achieve what you're trying to do, let's do the following.
first: allocate a new list to hold all the prices you are taking as input. lets call it price_list.
price_list = []
now let's take floating point input form the user for price and append it to the price_list
price = float(raw_input('Price for the item :'))
price_list.append(price)
now that we have a list of prices, lets get the sum of all the prices.
sum(price_list)
That should give you the total sum.
Hope it helps!

Categories