Pulling From Lists - list

You have a group of friends coming to visit for your high school reunion, and you want to take them out to eat at a local restaurant. You aren’t sure if any of them have dietary restrictions, but your restaurant choices are as follows:
Restaurant Vegetarian Vegan Gluten-Free
Joe's Gourmet Burgers NO NO NO
Main Street Pizza Company. YES NO YES
Corner Cafe YES YES YES
Mama's Fine Italian YES NO NO
The Chef's Kitchen YES YES YES
Complete the function that takes whether any members of your party are vegetarian, vegan, or gluten-free as inputs (True means "YES" and False means "NO"), and then return a list of only the restaurants to which you may take the group.
**Above is the the problem I am trying to solve. I think I am correct in creating the list but I don't know how to create the output of the restaurants that would be ok. Also, it would be great it was explained to me, I am a beginner in coding and trying to learn :). **
def chooseRestaurant(vegetarian,vegan,gluten_free):
restaurants = [
["Joe's Gourment Burgers", [False, False, False]],
['Main Street Pizza Company', [True, False, True]],
['Corner Cafe', [True, True, True]],
["Mama's Fine Italian", [True, False, False]]
["The Chef's Kitchen", [True, True, True]]
]
for x in returants:
if(False in x[1]):
print(x[0])
chooseRestaurant(True, False, True) #this is just a test case

Related

How to do nested Group By with Annotation in django orm?

I have the following data:
publisher title
-------------------------- -----------------------------------
New Age Books Life Without Fear
New Age Books Life Without Fear
New Age Books Sushi, Anyone?
Binnet & Hardley Life Without Fear
Binnet & Hardley The Gourmet Microwave
Binnet & Hardley Silicon Valley
Algodata Infosystems But Is It User Friendly?
Algodata Infosystems But Is It User Friendly?
Algodata Infosystems But Is It User Friendly?
Here is what I want to do: I want to count how many books of the same titles are published by each author.
I want to get the following result:
{publisher: New Age Books, title: Life Without Fear, count: 2},
{publisher: New Age Books, title: Sushi Anyone?, count: 1},
{publisher: Binnet & Hardley, title: The Gourmet Microwave, count: 1},
{publisher: Binnet & Hardley, title: Silicon Valley, count: 1},
{publisher: Binnet & Hardley, title: Life Without Fear, count: 1},
{publisher: Algodata Infosystems, title: But Is It User Friendly?, count: 3}
My solution goes something along the lines of:
query_set.values('publisher', 'title').annotate(count=Count('title'))
But it is not producing the desired result.
There is a peculiarity in Django that will not perform a GROUP BY on the values without an .order_by() clause. You can thus add an .order_by() clause and process this with:
query_set.values('publisher', 'title').annotate(
count=Count('pk')
).order_by('publisher', 'title')
By ordering the items "fold" into a group and we thus count the number of primary keys for each group.

Linear problem for chemical composition of a formulation

Dears,
I´m writing a Linear Program for optimization.
One of my goals is to recommend to my supplier which raw material mix to use in its product formulation in order to optimally fulfill my nutrient needs in several locations. Example:
Sets:
SET_RAW_MATERIALS = ['Ureia', 'Ammonium Sulphate']
SET_NUTRIENTS = ['Nitrogen', 'Sulfur'] # Two nutrients that are supplied through the available raw materials
SET_LOCATIONS = ['Location A', 'Location B'] # Two locations for having nutrient demands fulfilled
SET_FORMULATIONS = ['Formulation 1'] # I have only 1 formulation to propose to my supplier
Parameters:
PARAM_NUTRIENT_DEMAND = [
('Location A', 'Nitrogen'): 10,
('Location A', 'Sulfur'): 2,
('Location B', 'Nitrogen'): 10
]
PARAM_RAW_MATERIAL_NUTRIENT_CONTENT = [
('Ammonium Sulphate', 'Nitrogen'): 10,
('Ammonium Sulphate', 'Sulfur'): 5,
('Urea', 'Nitrogen'): 2
]
Variables:
VAR_CHEMICAL_COMPOSITION('Formulation', 'Raw_material') # For each formulation I should find the optimal content of each raw_material (ranging from 0 to 1) VAR_VOLUME_FORMULATION('Formulation', 'Location') # The volume that i should use on each location for the proposed formulation
Constraints:
(1) Nutrient demand (for each location and nutrient):
PARAM_NUTRIENT_DEMAND['Location', 'Nutrient'] <= sum(
VAR_VOLUME_FORMULATION['Formulation', 'Location'] * VAR_CHEMICAL_COMPOSITION['Formulation', 'Raw Material'] * PARAM_RAW_MATERIAL_NUTRIENT_CONTENT['raw_material', 'nutrient'] for all Raw Materials)
This is the only formulation I was able to come up with, but it is obviously non-linear. Is there any way to rewrite this constraint to have a LINEAR PROBLEM?
Thank you for the help.,
p.S.: I know the problem is not complete, I´ve brought only the information necessary to show the problem
you have a blending example with docplex at https://github.com/sumeetparashar/IBM-Decision-Optimization-Introductory-notebook/blob/master/Oil-blend-student-copy.ipynb
I also recommend diet example in
CPLEX_Studio1210\python\examples\mp\modeling

How to find item in list

I am new and have been working on this for a week now but can't find any solution. I hope someone can help me figure this out.
How can I find items in the list - listitems and output their items individually?
listitems = ['Beer, Chicken', 'Cake, Chocolate', 'Lemon with ci, Chicken', 'Beer, Beer, Cake, Chocolate']
Is there anyway i can compute the related food in the receipt list?
So far I am only able to find the foods for ONE item. My code is as follows:
I also computed another list of each item is for comparison.
eachitems = ['Beer', 'Cake', 'Chocolate', 'Lemon with ci', 'Chicken']
I would personally use a dictionary based on keys for each item with associated items as their values, would also be much easier for you to get the results you want, not exactly sure right know how I would accomplish it from the list you made only.
From your original code, add " print (combi) ", " print (checklist) " and " print (correlatedlist) " at the end and you will see it doesn't really append it the way you want.
In Python 3.5:
import itertools
listOfStrings = ['Beer, Chicken', 'Cake, Chocolate', 'Lemon with ci, Chicken', 'Beer, Beer, Cake, Chocolate']
print ('Original list:', listOfStrings)
print ()
listOfLists = [group.replace (', ', ',') .split (',') for group in listOfStrings]
print ('Turned into list of lists:', listOfLists)
print ()
allFoods = set (itertools.chain (*listOfLists))
print ('All individual foods:', allFoods)
print ()
listOfSets = [set (group) for group in listOfLists]
print ('A list of sets is handy, since sets contain no duplicates:', listOfSets)
print ()
dictOfFoods = dict ([[food, set ()] for food in allFoods])
print ('Prepare a dictionary, where we can put the associated foods:', dictOfFoods)
print ()
for food in dictOfFoods:
for foodSet in listOfSets:
if food in foodSet:
dictOfFoods [food] .update (foodSet)
dictOfFoods [food] .remove (food)
print ('The dictionary is now filled:', dictOfFoods)
print ()
for food in dictOfFoods:
print ('People who buy', food, 'also buy:')
for otherFood in dictOfFoods [food]:
print (otherFood)
print ()
Will print:
Original list: ['Beer, Chicken', 'Cake, Chocolate', 'Lemon with ci, Chicken', 'Beer, Beer, Cake, Chocolate']
Turned into list of lists: [['Beer', 'Chicken'], ['Cake', 'Chocolate'], ['Lemon with ci', 'Chicken'], ['Beer', 'Beer', 'Cake', 'Chocolate']]
All individual foods: {'Chocolate', 'Lemon with ci', 'Chicken', 'Cake', 'Beer'}
A list of sets is handy, since sets contain no duplicates: [{'Chicken', 'Beer'}, {'Chocolate', 'Cake'}, {'Chicken', 'Lemon with ci'}, {'Chocolate', 'Cake', 'Beer'}]
Prepare a dictionary, where we can put the associated foods: {'Chocolate': set(), 'Lemon with ci': set(), 'Cake': set(), 'Beer': set(), 'Chicken': set()}
The dictionary is now filled: {'Chocolate': {'Cake', 'Beer'}, 'Lemon with ci': {'Chicken'}, 'Cake': {'Chocolate', 'Beer'}, 'Beer': {'Chocolate', 'Chicken', 'Cake'}, 'Chicken': {'Lemon with ci', 'Beer'}}
People who buy Chocolate also buy:
Cake
Beer
People who buy Lemon with ci also buy:
Chicken
People who buy Cake also buy:
Chocolate
Beer
People who buy Beer also buy:
Chocolate
Chicken
Cake
People who buy Chicken also buy:
Lemon with ci
Beer
If you don't want to use itertools and *, you can also make a loop in a loop to traverse all elements of the listOfLists and add them to allFoods, which you initially make empty.
It took me sometime to understand exactly what you wanted, but this is a working solution.
listitems = ['Beer, Chicken', 'Cake, Chocolate', 'Lemon with ci, Chicken', 'Beer, Beer, Cake, Chocolate']
eachitems = ['Beer', 'Cake', 'Chocolate', 'Lemon with ci', 'Chicken']
for item in eachitems:
assoc = [associated for associated in listitems if item in associated]
result = set()
for itemlist in assoc:
itemlist = itemlist.replace(', ', ',').split(',')
itemlist = set(itemlist)
itemlist.remove(item)
result = result | itemlist
print('People who buy {} also buy: '.format(item), ', '.join(sorted(result)))
Output
People who buy Beer also buy: Cake, Chicken, Chocolate
People who buy Cake also buy: Beer, Chocolate
People who buy Chocolate also buy: Beer, Cake
People who buy Lemon with ci also buy: Chicken
People who buy Chicken also buy: Beer, Lemon with ci
They key part to this solution is the use of Sets to remove the duplicate items and the |(union) operator.
As a side note, instead of using | like this
result = result | itemlist
you can modify the set in place with
result.update(itemlist)

Search a list with words in string as parameter in python

I could use some advice, how to search in a list for genres with words in a string as parameter.
So if i have created a list called genre, which contains a string like:
['crime, drama,action']
I want to use this list to search for movies containing all genres or maybe just 1 of them.
I have created a big list which contains all information about the movie. An example from the list you see here:
('Saving Private Ryan (1998)', '8.5', "Tom Hanks, Matt Damon, Tom Sizemore',\n", 'action, drama, war,\n'),
So if i want to search for saving private ryan, which is a drama + action genre, but not crime, how can i then use my genre list to search for it?
Is there a way to search by something in the string?
UPDATE:
So this is what i done so far. I have tried to precess my tuple movie and use the def function.
Navn_rating = dict(zip(names1, ratings))
Actor_genre = dict(zip(actorlist, genre_list))
var = raw_input("Enter movie: ")
print "you entered ", var
for row in name_rating_actor_genre:
if var in row:
movie.append(row)
print "Movie found",movie
def process_movie(movie):
return {'title': names1, 'rating': ratings, 'actors': actorlist, 'genre': genre_list}
You can "search by something in the string" using in:
>>> genres = 'action, drama, war,\n'
>>> 'action' in genres
True
>>> 'drama' in genres
True
>>> 'romantic comedy' in genres
False
But note that this might not always give the result you want:
>>> 'war' in 'award-winning'
True
I think you should change your data structure. Consider making each movie a dictionary e.g.
{'title': 'Saving Private Ryan', 'year': 1998, 'rating': 8.5, 'actors': ['Tom Hanks', ...], 'genres': ['action', ...]}
then your query becomes
if 'drama' in movie.genres and 'action' in movie.genres:
You can use indexing, split and slicing to process your tuple of strings to make the values of the dictionary, e.g.:
>>> movie = ('Saving Private Ryan (1998)', '8.5', "Tom Hanks, Matt Damon, Tom Sizemore',\n", 'action, drama, war,\n')
>>> int(movie[0][-5:-1])
1998
>>> float(movie[1])
8.5
>>> movie[0][:-7]
'Saving Private Ryan'
>>> movie[2].split(",")
['Tom Hanks', ' Matt Damon', " Tom Sizemore'", '\n']
As you can see, some tidying up may be needed. You could write a function that takes the tuple as an argument and returns the corresponding dictionary:
def process_movie(movie_tuple):
# ... process the tuple here
return {'title': title, 'rating': rating, ...}
and apply this to your list of movies using map:
movies = list(map(process_movie, name_rating_actor_genre))
Edit:
You will know your function works when the following line doesn't raise any errors:
assert process_movie(('Saving Private Ryan (1998)', '8.5', "Tom Hanks, Matt Damon, Tom Sizemore',\n", 'action, drama, war,\n')) == {"title": "Saving Private Ryan", "year": 1998, "rating": 8.5, "actors": ["Tom Hanks", "Matt Damon", "Tom Sizemore"], "genres": ["action", "drama", "war"]}

Supplying a default value for left outer joins

I was wondering what would be the best way of specifying a default value when doing an outer-join in cascalog for field that could be null.
(def example-query
(<- [?id ?fname ?lname !days-active]
(users :> ?id ?fname ?lname)
(active :> ?fname ?lname !days-active))
In this example users and active would be previously defined queries and I'm just looking to correlate active user information (?fname ?lname !days-active) and regular user information (?id ?fname ?lname)
So when the join happened if there was no corresponding information for !days-active it would output 0 instead of nil
i.e.
392393 john smith 3
003030 jane doe 0
instead of
392393 john smith 3
003030 jane doe null
Updated Example
(<- [!!database-id ?feature !!user-clicks !!engaged-users ?application-id ?active-users]
(app-id-db-id-feature-clicks-engaged :> ?application-id !!database-id ?feature !!user-clicks !!engaged-users )
(user-info :> ?application-id ?feature ?active-users))]
example output would look something roughly like
4234 search null null 222 5000
3232 profile 500 400 331 6000
with the filtering that I'm interested I could change the fields that would be !!engaged-users and !!user-clicks to have 0 instead of null. Would using multiple Or predicates work?
I think what you want to do is add an or predicate:
(def example-query
(<- [?id ?fname ?lname !days-active]
(users :> ?id ?fname ?lname)
(active :> ?fname ?lname !days-active)
(or !days-active 0 :> ?active-days)))
That's not an outer join, by the way, it's just not filtering out null variables in the !days-active position.