understanding a python snippet about a boolean variable - python

I beginner in python & I don't know this line in the following is used for what? It's a Boolean value?(for & if in a sentence?) If anybody know it, please explain. Thanks
taken_match = [couple for couple in tentative_engagements if woman in couple]
###
for woman in preferred_rankings_men[man]:
#Boolean for whether woman is taken or not
taken_match = [couple for couple in tentative_engagements if woman in couple]
if (len(taken_match) == 0):
#tentatively engage the man and woman
tentative_engagements.append([man, woman])
free_men.remove(man)
print('%s is no longer a free man and is now tentatively engaged to %s'%(man, woman))
break
elif (len(taken_match) > 0):
...

Python has some pretty sweet syntax to create lists quickly. What you're seeing here is list comprehension-
taken_match = [couple for couple in tentative_engagements if woman in couple]
taken_match will be a list of all the couples where the woman is in the couple- basically, this filters out all the couples where the woman is NOT in the couple.
If we were to write this out without list comprehension:
taken_match = []
for couple in couples:
if woman in couple:
taken_match.append(couple)
As you can see.. list comprehension is way cooler :)
After that line, you're checking if the length of the taken_match is 0- if it is, no couples were found with that woman in them, so we add in an engagement between what the man and the woman, and then move on. If you have any other lines you didn't understand, feel free to ask!

Related

Less memory intensive way to parse large JSON file in Python

Here is my code
import json
data = []
with open("review.json") as f:
for line in f:
data.append(json.loads(line))
lst_string = []
lst_num = []
for i in range(len(data)):
if (data[i]["stars"] == 5.0):
x = data[i]["text"]
for word in x.split():
if word in lst_string:
lst_num[lst_string.index(word)] += 1
else:
lst_string.append(word)
lst_num.append(1)
result = set(zip(lst_string, lst_num))
print(result)
with open("set.txt", "w") as g:
g.write(str(result))
I'm trying to write a set of all words in reviews that were given 5 stars from a pulled in json file formatted like
{"review_id":"Q1sbwvVQXV2734tPgoKj4Q","user_id":"hG7b0MtEbXx5QzbzE6C_VA","business_id":"ujmEBvifdJM6h6RLv4wQIg","stars":1.0,"useful":6,"funny":1,"cool":0,"text":"Total bill for this horrible service? Over $8Gs. These crooks actually had the nerve to charge us $69 for 3 pills. I checked online the pills can be had for 19 cents EACH! Avoid Hospital ERs at all costs.","date":"2013-05-07 04:34:36"}
{"review_id":"GJXCdrto3ASJOqKeVWPi6Q","user_id":"yXQM5uF2jS6es16SJzNHfg","business_id":"NZnhc2sEQy3RmzKTZnqtwQ","stars":1.0,"useful":0,"funny":0,"cool":0,"text":"I *adore* Travis at the Hard Rock's new Kelly Cardenas Salon! I'm always a fan of a great blowout and no stranger to the chains that offer this service; however, Travis has taken the flawless blowout to a whole new level! \n\nTravis's greets you with his perfectly green swoosh in his otherwise perfectly styled black hair and a Vegas-worthy rockstar outfit. Next comes the most relaxing and incredible shampoo -- where you get a full head message that could cure even the very worst migraine in minutes --- and the scented shampoo room. Travis has freakishly strong fingers (in a good way) and use the perfect amount of pressure. That was superb! Then starts the glorious blowout... where not one, not two, but THREE people were involved in doing the best round-brush action my hair has ever seen. The team of stylists clearly gets along extremely well, as it's evident from the way they talk to and help one another that it's really genuine and not some corporate requirement. It was so much fun to be there! \n\nNext Travis started with the flat iron. The way he flipped his wrist to get volume all around without over-doing it and making me look like a Texas pagent girl was admirable. It's also worth noting that he didn't fry my hair -- something that I've had happen before with less skilled stylists. At the end of the blowout & style my hair was perfectly bouncey and looked terrific. The only thing better? That this awesome blowout lasted for days! \n\nTravis, I will see you every single time I'm out in Vegas. You make me feel beauuuutiful!","date":"2017-01-14 21:30:33"}
{"review_id":"2TzJjDVDEuAW6MR5Vuc1ug","user_id":"n6-Gk65cPZL6Uz8qRm3NYw","business_id":"WTqjgwHlXbSFevF32_DJVw","stars":1.0,"useful":3,"funny":0,"cool":0,"text":"I have to say that this office really has it together, they are so organized and friendly! Dr. J. Phillipp is a great dentist, very friendly and professional. The dental assistants that helped in my procedure were amazing, Jewel and Bailey helped me to feel comfortable! I don't have dental insurance, but they have this insurance through their office you can purchase for $80 something a year and this gave me 25% off all of my dental work, plus they helped me get signed up for care credit which I knew nothing about before this visit! I highly recommend this office for the nice synergy the whole office has!","date":"2016-11-09 20:09:03"}
{"review_id":"yi0R0Ugj_xUx_Nek0-_Qig","user_id":"dacAIZ6fTM6mqwW5uxkskg","business_id":"ikCg8xy5JIg_NGPx-MSIDA","stars":1.0,"useful":0,"funny":0,"cool":0,"text":"Went in for a lunch. Steak sandwich was delicious, and the Caesar salad had an absolutely delicious dressing, with a perfect amount of dressing, and distributed perfectly across each leaf. I know I'm going on about the salad ... But it was perfect.\n\nDrink prices were pretty good.\n\nThe Server, Dawn, was friendly and accommodating. Very happy with her.\n\nIn summation, a great pub experience. Would go again!","date":"2018-01-09 20:56:38"}
{"review_id":"yi0R0Ugj_xUx_Nek0-_Qig","user_id":"dacAIZ6fTM6mqwW5uxkskg","business_id":"ikCg8xy5JIg_NGPx-MSIDA","stars":5.0,"useful":0,"funny":0,"cool":0,"text":"a b aa bb a b","date":"2018-01-09 20:56:38"}
but it is using all the memory on my computer before it can output into a text file. How can I use a less memory intensive way?
Only get text where stars == 5:
Data:
Based on the question, the data is a file containing rows of dicts.
Get the text into a list:
Given the data from Yelp Challenge, getting the 5 stars text into a list, doesn't take that much memory.
The Windows resource manager showed an increase of about 1.3GB, but the object size of text_list was about 25MB.
import json
text_list = list()
with open("review.json", encoding="utf8") as f:
for line in f:
line = json.loads(line)
if line['stars'] == 5:
text_list.append(line['text'])
print(text_list)
>>> ['Test text, example 1!', 'Test text, example 2!']
Extra:
Everything after loading the data, seems to require a lot of memory that isn't being released.
When cleaning the text, Windows resource manager went up by 16GB, though the final size of clean_text was also only about 25MB.
Interestingly, deleting clean_text does not release the 16GB of memory.
In Jupyter Lab, restarting the Kernel will release the memory
In PyCharm, stopping the process also releases the memory
I tried manually running the garbage collector, but that didn't release the memory
Clean text_list:
import string
def clean_string(value: str) -> list:
value = value.lower()
value = value.translate(str.maketrans('', '', string.punctuation))
value = value.split()
return value
clean_text = [clean_string(item) for item in text_list]
print(clean_text)
>>> [['test', 'text', 'example', '1'], ['test', 'text', 'example', '2']]
Count words in clean_text:
from collection import Counter
words = Counter()
for item in clean_text:
words.update(item)
print(words)
>>> Counter({'test': 2, 'text': 2, 'example': 2, '1': 1, '2': 1})

The usage of radix sort

Let's say i have a file containing data on users and their favourite movies.
Ace: FANTASTIC FOUR, IRONMAN
Jane: EXOTIC WILDLIFE, TRANSFORMERS, NARNIA
Jack: IRONMAN, FANTASTIC FOUR
and based of that, the program I'm about to write returns me the name of the users that likes the same movies.
Since Ace and Jack likes the same movie, they will be partners hence the program would output:
Movies: FANTASTIC FOUR, IRONMAN
Partners: Ace, Jack
Jane would be exempted since she doesn't have anyone who shares the same interest in movies as her.
The problem I'm having now is figuring out on how Radix Sort would help me achieve this as I've been thinking whole day long. I don't have much knowledge on radix sort but i know that it compares elements one by one but I'm terribly confused in cases such as FANTASTIC FOUR being arranged first in Ace's data and second in Jack's data.
Would anyone kindly explain some algorithms that i could understand to achieve the output?
Can you show us how you sort your lists ? The quick and dirty code below give me the same output for sorted Ace and Jack.
Ace = ["FANTASTIC FOUR", "IRONMAN"]
Jane = ["EXOTIC WILDLIFE", "TRANSFORMERS", "NARNIA"]
Jack = ["IRONMAN", "FANTASTIC FOUR"]
sorted_Ace = sorted(Ace)
print (sorted_Ace)
sorted_Jack = sorted(Jack)
print (sorted_Jack)
You could start comparing elements one by one from here.
I made you a quick solution, it can show you how you can proceed as it's not optimized at all and not generalized.
Ace = ["FANTASTIC FOUR", "IRONMAN"]
Jane = ["EXOTIC WILDLIFE", "TRANSFORMERS", "NARNIA"]
Jack = ["IRONMAN", "FANTASTIC FOUR"]
Movies = []
Partners = []
sorted_Ace = sorted(Ace)
sorted_Jane = sorted(Jane)
sorted_Jack = sorted(Jack)
for i in range(len(sorted_Ace)):
if sorted_Ace[i] == sorted_Jack[i]:
Movies.append(sorted_Ace[i])
if len(Movies) == len(sorted_Ace):
Partners.append("Ace")
Partners.append("Jack")
print(Movies)
print(Partners)

Python counting characters in a line

It's supposed to count the amount of lines and the amount of characters in the line.
I cannot add any more variables to my display function, as the professor said to use 2.
I've gotten it to count the characters in the line correctly if I change the zXX= zXX + 1
to zXX = w
but if i do that it will not count the number of lines, if someone could help I'd greatly appreciate it.
Currently I have:
def display(x, y):
y = str(y)
varx = str(len(y))
vary = y + "#" + x + "#" + varx
return vary.rjust(3)
def main():
script = '''Grandson|Cough, cough, cough. Cough, cough, cough. {Grandson is on the bed, playing video game.} Mother|{Enters.} Hi, honey. Grandson|Hi, Mom. Mother|{Kisses son and feels his forehead.} You feeling any better? Grandson|A little bit. Mother|Guess what? Grandson|What? Mother|Your Grandfather's here. {Opens curtains.} Grandson|Mom, can't you tell him I'm sick? Mother|You're sick? That's why he's here. Grandson|He'll pinch my cheek. I hate that. Mother|Maybe he won't. Grandfather|{Entering with a flourish.} Heyyyy!! How's the sickie? Heh? {Pinches boy's cheek. Boy looks at mother accusingly.} Mother|I think I'll leave you two pals alone. {Exits.} Grandfather|I brought you a special present. Grandson|What is it? Grandfather|Open it up. Grandson|{Opens the package. Disappointed.} A book? Grandfather|That's right. When I was your age, television was called books. And this is a special book. It was the book my father used to read to me when I was sick, {takes book} and I used to read it to your father. And today I'm gonna read it to you. Grandson|Has it got any sports in it? Grandfather|Are you kidding? Fencing, fighting, torture, revenge, giants, monsters, chases, escapes, true love, miracles... Grandson|Doesn't sound too bad. I'll try to stay awake. {Turns off TV.} Grandfather|Oh, well, thank you very much, very nice of you. Your vote of confidence is overwhelming. All right. {Puts glasses on.} The Princess Bride, by S. Morgenstern. Chapter One. Buttercup was raised on a small farm in the country of Florin.'''
zX = script.split('\n')
#print(zX)
zXX = 0
for w in zX:
#print(zX[zXX:(zXX + 1)])
zXXXX = w.split('|')
#print(zXXXX)
zXXX = zXXXX[0].upper() + " " + zXXXX[1]
#print(zXXX)
zXX = zXX + 1
print(display(zXXX, zXX))
main()
The output is:
1#GRANDSON Cough, cough, cough. Cough, cough, cough. {Grandson is on the bed, playing video game.}#1
2#MOTHER {Enters.} Hi, honey.#1
3#GRANDSON Hi, Mom.#1
4#MOTHER {Kisses son and feels his forehead.} You feeling any better?#1
5#GRANDSON A little bit.#1
6#MOTHER Guess what?#1
7#GRANDSON What?#1
8#MOTHER Your Grandfather's here. {Opens curtains.}#1
9#GRANDSON Mom, can't you tell him I'm sick?#1
10#MOTHER You're sick? That's why he's here.#2
11#GRANDSON He'll pinch my cheek. I hate that.#2
12#MOTHER Maybe he won't.#2
13#GRANDFATHER {Entering with a flourish.} Heyyyy!! How's the sickie? Heh?
{Pinches boy's cheek. Boy looks at mother accusingly.}#2
14#MOTHER I think I'll leave you two pals alone. {Exits.}#2
15#GRANDFATHER I brought you a special present.#2
16#GRANDSON What is it?#2
17#GRANDFATHER Open it up.#2
18#GRANDSON {Opens the package. Disappointed.} A book?#2
19#GRANDFATHER That's right. When I was your age, television was called books. And this is a special book. It was the book my father used to read to me when I was sick, {takes book} and I used to read it to your father. And today I'm gonna read it to you.#2
20#GRANDSON Has it got any sports in it?#2
21#GRANDFATHER Are you kidding? Fencing, fighting, torture, revenge, giants, monsters, chases, escapes, true love, miracles...#2
22#GRANDSON Doesn't sound too bad. I'll try to stay awake. {Turns off TV.}#2
23#GRANDFATHER Oh, well, thank you very much, very nice of you. Your vote of confidence is overwhelming. All right. {Puts glasses on.} The Princess Bride, by S. Morgenstern. Chapter One. Buttercup was raised on a small farm in the country of Florin.#2
Once I got past the formatting, and variable names, and that you didn't include the line breaks in 'script', I'm pretty sure that the issue is that you have:
varx = str(len(y))
Instead of:
varx = str(len(x))
Though that is based on my interpretation of what you provided

Two way matching for Secret Santa game [duplicate]

This question already has answers here:
Secret santa algorithm
(9 answers)
Closed 7 years ago.
I am trying to write a script that pairs up men and women for a secret Santa type event. So I have 2 lists of boys and girls, and want to carry out 2 way matching, but at the moment I can only seem to figure out how to do 1 way matching.
Furthermore the problem I have is this... in the example below if Kedrick gets Annabel, then Annabel can't get Kedrick. Kedrick has to get someone else from the list.
My current implementation is as follows, how can I extend its functionality to meet the abovementioned requirements?
boys = ['Kedrick','Jonathan','Tim','Philip','John','Quincy'];
girls = ['Annabel','Janet','Jocelyn','Pamela','Priscilla','Viviana'];
matches = []
for i in boys:
rand - randint(0, len(girls-1)
fullname = "{} matched with {}".format(i, girls(rand)
del girls(rand)
matches.append(fullname)
print matches
This could probably be done with fewer loops and a lot less code but here is my solution! Created 2 dict's to store names and their targets (dict's could be combined or done at the same time to cut down on memory issues, but with a program this size I don't think you would ever run into this issue!
boys = ['Kedrick','Jonathan','Tim','Philip','John','Quincy'];
girls = ['Annabel','Janet','Jocelyn','Pamela','Priscilla','Viviana'];
matchesBoys = {i:{'to':''} for i in boys}
matchesGirls = {i:{'to':''} for i in girls}
for name in boys:
giveTo = girls[random.randint(0, len(girls)-1)]
girls.remove(giveTo)
matchesBoys[name]['to']=giveTo
for name in matchesGirls:
giveTo = boys[random.randint(0, len(boys)-1)]
boys.remove(giveTo)
matchesGirls[name]['to']=giveTo
del boys, girls
for i in matchesBoys:
print "%s matched with %s"%(i, matchesBoys[i]['to'])
for i in matchesGirls:
print '%s matched with %s'%(i, matchesGirls[i]['to'])
Shuffle both lists and put them in a ring, with every other element being from the first or second list. Each person gives a gift to the one on their right. Something similar to a list like this:
[Girl, Boy, Girl, Boy, ..., Boy]
The last element gives a gift to the first.
It works under the assumption that both lists have the same amount of elements and that there are at least four elements in total, otherwise the problem is unsolvable.
This gives one solution that fulfills your constraints. The general solution to the problem is to find a directed bipartite graph between the sets where each vertex have exactly two edges, one incoming and one outgoing. Perhaps the solution to that problem also always creates a ring?
This is an implementation that creates a circle with alternate boy and girl. See #Emil Vickstom's answer for an explanation of the idea.
from random import shuffle
boys = ['Kedrick','Jonathan','Tim','Philip','John','Quincy'];
girls = ['Annabel','Janet','Jocelyn','Pamela','Priscilla','Viviana'];
shuffle(boys)
shuffle(girls)
circle = [person for pair in zip(boys, girls) for person in pair]
print(' -> '.join(circle + circle[:1]))
Output:
Tim -> Priscilla -> Quincy -> Annabel -> John -> Janet -> Kedrick ->
Jocelyn -> Philip -> Pamela -> Jonathan -> Viviana -> Tim

Pulling raw_input options form a list

Hi I'm just starting to learn Python, I'm using the book "learn python the hard way" and one of the exercises is to build a simple game. I wanted to give options to the user from a list.
For example I would make a list called animals which would include 3 animals, lion tiger and fish. is is possible to offer selected elements from a list. I'm pretty sure it is but I just don't know how.
I was thinking something like this (obviously wrong but I think it helps to understand what I mean)
animals = ['Lion', 'Tiger', 'Fish']
print "which of these animals is your favourite?"
favourite = raw_input(animals[0] or animals[2])
if favourite = "Lion':
print "Nice choice"
else:
print "Bad choice"
Again I can't stress enough I know the above is really crap but essentially I want to offer certain items of a list as an option for the raw_input. In the above case the 0 item and the 2 item.
Thanks in advance for the help.
favourite = raw_input(' or '.join(animals))
This will take all the strings from the list animals and join them together with or in between, so you'll end up with
Lion or Tiger or Fish
if you want to add a question mark and space to the end, you can do
favourite = raw_input(' or '.join(animals) + '? ')
Also, on the line
if favourite = "Lion':
Your quotes don't match -- make sure to use either double or single quotes, not one of each. You also need to use == to compare two things; = is for assigning a value, not comparing.
I would probably do it like
animal_string = ' or '.join(animals)
favourite = raw_input("Which of these animals is your favourite:\n{}? ".format(animal_string))
Which first makes the animal string, then formats the choices into the question on a new line (because of the \n), and puts ? after.
How about this?
favourite = raw_input("which of these animals is your favourite? "+",".join([str(a)+":"+b for a,b in enumerate(animals)])+">")
fav = animals[int(favourite)]
print fav+" is a nice choice indeed!. The big bear will kill you anyway. Good bye."

Categories

Resources