This question already has answers here:
Python's "in" set operator
(6 answers)
Closed 1 year ago.
i am practicing sets in python and wrote the below script to search books. it works but not proper ly(please see it below). How can i fix the problem?
book_set = {"Harry Potter", "Angels and Demons", "Atlas Shrugged"}
q = input('Search our Catalog: ')
for book in book_set:
if book == q:
print(book)
else:
print('sorry We ran out of this book')
my expected result should be the title of book if present and the strint('sorry We ran out of this book') if the book doesn't exists in book_set without any more results but see the example
enter code here
Output
Search our Catalog: Harry Potter
Harry Potter
sorry We ran out of this book
You can use in keyword instead of for loop:
book_set = {"Harry Potter", "Angels and Demons", "Atlas Shrugged"}
q = input('Search our Catalog: ')
print("We have that book" if q in book_set "We don't have that book")
The problem you have is that you are going through every book and if it is the book you print it but if it isn't you say you ran out, but for every single book. What you probably want to do is only say you ran out if the book isn't in the set which you can do by doing
book_set = {"Harry Potter", "Angels and Demons", "Atlas Shrugged"}
q = input('Search our Catalog: ')
if q not in book_set:
print("We don't have that book")
else:
# code for when the book is in stock
Related
I'm struggling a bit on a dictionary code in Python (mind I'm a new student without any earlier experience). The strings in this code is on Norwegian, hopefully that's not a problem. The code goes as follow
participants_and_allergens = {"Ole":["gluten", "egg"],
"Silje":["shellfish", "nuts"],
"Ragnar":["milk", "fish"]}
print(participants_and_allergens.keys())
allergens_and_foods = {"Garlic bread": ["gluten", "egg"],
"Fish soup": ["shellfish", "fish"],
"Chocolate Cake": ["milk", "egg"]}
def write_name():
name = input("What is your name?\n> ")#confirms the registration of the participant
if not participants_og_allergener.get(name):
print("Sorry,", name + " does not exist in the registry")
else:
print(name + " is registered and now confirmed")
print(allergens)
print(name + " has the allergens", allergens)
allergens = participants_og_allergener.get(name)
allergens_foods = allergens_and_foods.get("allergens")
print(allergens_foods)
write_name()
Essentially, what I'm asking is, is there any way to connect to dictionaries, which are independent? When the user enters a name, it should result in values linked to the name coming out, and elements from another dictionary.
I have realized I'll have to use a for loop, but I don't know how.
The expected output should be something like "Hi Ole, you have allergies to gluten and eggs and should stay away from the foods garlic bread and chocolate cake"
I'm trying to get through my first semester of Python and am struggling. My dictionary is correct however, I cannot get what I want. I need the user to input a patient ID and then the program will display the ID with the name linked to it in the dictionary as the name is the value. Then if the user enters an ID that is not in the dictionary the computer tells them so. If they enter done the program says DONE! When numbers are entered the program needs to continue asking the question until done is typed. Here is was I have so far:
patientinfo = {}
lines = open('PatientsNames.txt')
lines.readline()
for line in lines:
id=line[:8]
if id not in patientinfo:
endlastname = line.find(' ', 8)
lastname = line[8:endlastname]
firstname = line[endlastname+1:]
patientinfo[id] = lastname + ', ' + firstname
answer = raw_input("Enter an ID ('done' to exit)")
try:
if answer in patientinfo.keys():
print answer, patientinfo(val)
except:
if answer not in patientinfo.keys():
print 'No patient with that ID'
else:
if answer='done':
print 'DONE!'
Attempting to add authors and their book titles to a list inside of a dictionary so that each author can support multiple book titles. In the code, I have 3 authors already and each has 1 book title, but they need to be able to support at least 1 more book title.
I have the values (book titles) of the keys (authors) nested inside of a list inside the dictionary already, but I don't know how to append more values to the existing keys that are inside of the existing list.
readings = {'George Orwell': ['1984'], 'Harper Lee': ['To Kill a Mockingbird'], 'Paul Tremblay': ['The Cabin at the End of the World']} # list inside of dict.
I need to use the following code to append the new book titles to the list
def add(readings): # appending to list will go here
author = input('\nEnter an author: ')
if author in readings: # check if input already inside dict.
bookTitle = readings[author]
print(f'{bookTitle} is already added for this author.\n')
else:
bookTitle = input('Enter book title: ')
bookTitle = bookTitle.title()
readings[author] = bookTitle
print(f'{bookTitle} was added.\n')
I expect that you are not able to add the same book title twice and not be able to add the same author twice either. I am expected to be able to input book titles for an existing author (or new author not already existing) while the program is running, then be able to view all of the authors and their book title(s) via a 'command menu' (not shown).
You're workflow is a little off. After checking for the author, then check for the book in the list of books by that author. You can add a title to the list of books using .append. Try this:
def add(readings): # appending to list will go here
author = input('\nEnter an author: ')
if author in readings: # check if input already inside dict.
books = readings[author]
print(f'Found {len(books)} books by {author}:')
for b in books:
print(f' - {b}')
else:
readings[author] = []
bookTitle = input('Enter book title: ')
bookTitle = bookTitle.title()
if bookTitle in readings[author]:
print(f'{bookTitle} is already added for this author.')
else:
readings[author].append(bookTitle)
print(f'Add "{bookTitle}"')
So you are trying to add multiple books to an author, is that correct? Since the values in your dictionary are already stored as list, you can try doing -
readings[author].append(bookTitle)
instead of
readings[author] = bookTitle
So I've got this bot that I want to use to reply with the box score of the mets game anytime someone says "mets score" on a specific subreddit. This is my first python project and I plan on using it on a dummy subreddit I created as a learning tool. I'm having trouble sending the scores from the website I scraped through the bot so it can appear in the reply to the "mets score" comments. Any suggestions?
import praw
import time
from lxml import html
import requests
from bs4 import BeautifulSoup
r = praw.Reddit(user_agent = 'my_first_bot')
r.login('user_name', 'password')
def scores():
soup = BeautifulSoup(requests.get("http://scores.nbcsports.com/mlb/scoreboard.asp?day=20160621&meta=true").content, "lxml")
table = soup.find("a",class_="teamName", text="NY Mets").find_previous("table")
a, b = [a.text for a in table.find_all("a",class_="teamName")]
inn, a_score, b_score = ([td.text for td in row.select("td.shsTotD")] for row in table.find_all("tr"))
print (" ".join(inn))
print ("{}: {}".format(a, " ".join(a_score)))
print ("{}: {}".format(b, " ".join(b_score)))
words_to_match = ['mets score']
cache = []
def run_bot():
print("Grabbing subreddit...")
subreddit = r.get_subreddit("random_subreddit")
print("Grabbing comments...")
comments = subreddit.get_comments(limit=40)
for comment in comments:
print(comment.id)
comment_text = comment.body.lower()
isMatch = any(string in comment_text for string in words_to_match)
if comment.id not in cache and isMatch:
print("match found!" + comment.id)
comment.reply('heres the score to last nights mets game...' scores())
print("reply successful")
cache.append(comment.id)
print("loop finished, goodnight")
while True:
run_bot()
time.sleep(120)
I think I'll just put you out of your misery ;). There are multiple issues with your code snippet:
comment.reply('heres the score to last nights mets game...' scores())
The .reply() method requires a string or an object that can have a good enough representation as a string. Assuming the method scores() returns a string, you should concatenate the two arguments, like this:
comment.reply('heres the score to last nights mets game...'+ scores())
It looks like your knowledge of basic python syntax and constructs is dusty. For a quick refresher see this.
Your method scores() doesn't return anything. It just prints out a bunch of lines (which I assume are for debugging purposes).
def scores():
soup = BeautifulSoup(requests.get("http://scores.nbcsports.com/mlb/scoreboard.asp?day=20160621&meta=true").content, "lxml")
.......
print (" ".join(inn))
print ("{}: {}".format(a, " ".join(a_score)))
print ("{}: {}".format(b, " ".join(b_score)))
Funnily enough you could use those exact strings for your return value (or maybe something else entirely, as suit your needs) like this:
def scores():
.......
inn_string = " ".join(inn)
a_string = "{}: {}".format(a, " ".join(a_score))
b_string = "{}: {}".format(b, " ".join(b_score))
return "\n".join([inn_string, a_string, b_string])
These should get you up and running.
More advice: Have you read the Reddit PRAW docs? You should. You should also probably use praw.helpers.comment_stream(). It's simple and easy to use and will handle retrieving new comments for you. Currently you try and fetch a maximum of 40 comments every 120 seconds. What happens when there are more than that many relevant comments in that 120 second span. You'll end up missing some of the comments you should've replied to. .comment_stream() will take care of rate limiting for you so that your bot can reply to each new comment which needs its attention at its own pace. Read more about this here.
I am currently trying to write a program which runs through a CSV file of academic papers. The CSV is tab deliminated and is in four columns (Author, Date, Title, Journal)
The idea is to ask the user whether he wants to search the group of papers via Author, Paper Title or Journal Title (or press Q to quit), and display the results of the query back to the user in this order: Author/s. Year. Title. Journal.
My code runs, but it only retrieves data from the 'search option' I selected. I.E, if I choose to search by Author, it will pull back and display the Authors whose names match the query, but it doesn't display any of the other information (The year, title or journal). This is the same with the other search options (i.e if I select Journal, it will pull back any relevant journals but will not give me the Author, Date or Title of said journal)
Any help here is greatly appreciated! Below is my code.
import csv
def AuthorSearch():
authorSearch = input("Please type Author name. \n")
for item in Author:
if item.find(authorSearch) != -1:
print (item)
def TitleSearch():
titleSearch = input("Please type in Title, \n")
for item in Title:
if item.find(titleSearch) != -1:
print (item)
def JournalSearch():
journalSearch = input("Please type in a Journal, \n")
for item in Journal:
if item.find(journalSearch) != -1:
print (item)
data = csv.reader (open('List.txt', 'rt'), delimiter='\t')
Author, Year, Title, Journal = [], [], [], []
for row in data:
Author.append(row[0])
Year.append(row[1])
Title.append(row[2])
Journal.append(row[3])
print ("Please type in capitals.")
searchOption = input("Press A to search for Author, T to search titles or J to search Journals or press Q to quit. \n" )
if searchOption == 'A':
AuthorSearch()
elif searchOption == 'T':
TitleSearch()
elif searchOption == 'J':
JournalSearch()
elif searchOption == 'Q':
exit()
Thank you very much to anybody who helps, it's really appreciated!
I have googled and read the CSV reference page, but I can't seem to get my head around it. Aagin, all help is appreciated!
The list Author doesn't contain anything but the authors. When you do for item in Author, you are only looking through the authors. When you then print the found item, it is of course only the author. You have the same problem with each field. You have four separate lists of fields that are not linked in any way.
I would suggest you take a look at the pandas library, which has nice facilities for reading CSV files into a tabular data structure. It also does a lot more than that, but it should easily handle what you want to do here.
Your issue is that you put all your info into separate arrays...but you did that because you know their column numbers...so just keep it as is and call by the number!
everything = []
for row in data:
everything.append[row]
Here is an example for your title search function:
def TitleSearch():
titleSearch = input("Please type in Title, \n")
for row in everything:
title = row[2]
if title.find(titleSearch) != -1:
print row
so now you take the entire row, and just run your find() on the 3rd column (the one you said was title) and if it's the same as your titleSearch it will print the entire row with all of the information, problem solved!