Python 2.7 Error - can't get past an error - python-2.7

I keep getting the
"too many variables to unpack"
error. Can anybody help me get this working, and possibly give me an explanation?
wings_quantity = {
'small' : 8,
'medium' : 14,
'large' : 20,
'half bucket' : 30,
'bucket' : 65,
}
wings_price = {
'small' : 5.99,
'medium' :8.50,
'large' : 14.00,
'half bucket' :20.00,
'bucket' : 55.00
}
for number, key in wings_quantity:
print " "
print "There are "+(str(wings_quantity[number]))+ " wings in a "+(wings_quantity[key])+" size."
print " "
for number, key in wings_quantity:
ppw = wings_quantity[number] / wings_price[number]
print ('The cost per wing in a %s size is $') + ppw %wing_quantity[key]

You are close, but you forgot to put the iteritems() on the end of your for statements.
Change
for number, key in wings_quantity:
to
for number, key in wings_quantity.iteritems():
After that problem you need to rewrite your print statements as they are trying to access the dictionary twice. Since you already have the values you can just print them like so:
print "There are "+ key + " wings in a "+ str(value) +" size."
I tested this in 3.4 and it worked, but in 3.x you need to change it to
for number, key in wings_quantity.items():
This produced this output for the first loop
There are bucket wings in a 65 size.
There are small wings in a 8 size.
There are medium wings in a 14 size.
There are half bucket wings in a 30 size.
There are large wings in a 20 size.

Related

list index is out of range in try/raise/exception

I have the following code:
for i in range(len(str(hoursList))):
try:
g(hoursList[i])
except Exception as ex:
print(str(nameList[i]) + " " + "has more than 80 hours worked!")
When I run the code, I get an error saying "IndexError: list index out of range". I'm wondering if its because I have hoursList[i], but when I take out the [i], the loop runs too many times.
My nameList and hoursList has the following in it, respectively.
['Michael Johnson', 'Sue Jones', 'Tom Spencer', 'Mary Harris', 'Alice Tolbert', 'Joe Sweeney', 'Linda Smith', 'Ted Farmer', 'Ruth Thompson', 'Bob Bensen']
[8.75, 8.75, 8.75, 8.75, 8.75, 8.75, 11.0, 11.0, 5.25, 5.0]
What is happening when you are doing len(str(hoursList)) is you are turning the entire list into a string then going through and returning an i for each number, space, and , of the new string. For example:
len(str(["hello", "world"])) == 18
But if you do this:
len(["hello", "world"]) == 2
So when you are in the for i loop you end up going over how many entries are actually in the hoursList.
Change your loop to be:
for i in range(len(hoursList)):
try:
g(hoursList[i])
except Exception as ex:
print(str(nameList[i]) + " " + "has more than 80 hours worked!")

I'm getting a SyntaxError | I'm learning from Learn Python The Hard Way

This is my code it's the exact same code as the pdf
states = [
"Oregon":"OR",
"Florida": "FL",
"California": "CA",
"New York": "NY",
"Michigan": "MI"
]
cities = [
"CA": "San Francisco",
"MI": "Detroit",
"FL": "Jacksonville"
]
cities["NY"] = "New York"
cities["OR"] = "Portland"
print "-" * 10
print "NY state has: ", cities["NY"]
print "OR state has: ", cities["OR"]
print "-" * 10
print "Michigan's abbreviation is: ", states["Michigan"]
print "Florida's abbreviation is: ", states["Florida"]
print "-" * 10
print "Michigan has: ", cities[states["Michigan"]]
print "Florida has: ", cities[states["Florida"]]
print "-" * 10
for state, abbrev in states.items():
print "%s is abbreviated %s", % (state, abbrev)
print "-" * 10
for abbrev, city in cities.items():
print "%s has the city %s" % (abbrev, city)
print "-" * 10
for state, abbrev in states.items():
print "%s state is abbreviated %s and has city %s" % (
state, abbrev, cities[abbrev])
print "-" * 10
state = states.get("Texas", None)
if not state:
print "Sorry, no Texas."
city = cities.get("TX", "Does Not Exist")
print "The city for the state 'TX' is: %s" % city
This is my error i put into my terminal python ex39.py and i get this.
File "ex39.py", line 3
"Oregon":"OR",
^
SyntaxError: invalid syntax
i'm running macOS 10.13.6 Beta (17G47b)
MacBook (13-inch, Mid 2010)
Processor 2.4 GHz Intel Core 2 Duo
Memory 8 GB 1067 MHz DDR3
Graphics NVIDIA GeForce 320M 256 MB
So the issue here is when you use brackets [] it makes a list, like [1,2,3,4,5].
While 1-5 in that list are all in the same list, they don't directly interact with each other.
You're looking for a dictionary, which uses curly brackets {}. It takes a array of information, but it takes them in pairs of a key and its value.
So you need this
states = {
"Oregon":"OR",
"Florida": "FL",
"California": "CA",
"New York": "NY",
"Michigan": "MI"
}
cities = {
"CA": "San Francisco",
"MI": "Detroit",
"FL": "Jacksonville"
}
The first of the pair is they key, the second is the value.
Hope this helps! Happy coding!

Python: How to calculate tf-idf for a large data set

I have a following data frame df, which I converted from sframe
URI name text
0 <http://dbpedia.org/resource/Digby_M... Digby Morrell digby morrell born 10 october 1979 i...
1 <http://dbpedia.org/resource/Alfred_... Alfred J. Lewy alfred j lewy aka sandy lewy graduat...
2 <http://dbpedia.org/resource/Harpdog... Harpdog Brown harpdog brown is a singer and harmon...
3 <http://dbpedia.org/resource/Franz_R... Franz Rottensteiner franz rottensteiner born in waidmann...
4 <http://dbpedia.org/resource/G-Enka> G-Enka henry krvits born 30 december 1974 i...
I have done the following:
from textblob import TextBlob as tb
import math
def tf(word, blob):
return blob.words.count(word) / len(blob.words)
def n_containing(word, bloblist):
return sum(1 for blob in bloblist if word in blob.words)
def idf(word, bloblist):
return math.log(len(bloblist) / (1 + n_containing(word, bloblist)))
def tfidf(word, blob, bloblist):
return tf(word, blob) * idf(word, bloblist)
bloblist = []
for i in range(0, df.shape[0]):
bloblist.append(tb(df.iloc[i,2]))
for i, blob in enumerate(bloblist):
print("Top words in document {}".format(i + 1))
scores = {word: tfidf(word, blob, bloblist) for word in blob.words}
sorted_words = sorted(scores.items(), key=lambda x: x[1], reverse=True)
for word, score in sorted_words[:3]:
print("\tWord: {}, TF-IDF: {}".format(word, round(score, 5)))
But this is taking a lot of time as there are 59000 documents.
Is there a better way to do it?
I am confused about this subject. But I found a few solution on the internet with use Spark. Here you can look at:
https://www.linkedin.com/pulse/understanding-tf-idf-first-principle-computation-apache-asimadi
On the other hand i tried theese method and i didn't get bad results. Maybe you want to try :
I hava a word list. This list contains word and it's counts.
I found the average of this words counts.
I selected the lower limit and the upper limit with the average value.
(e.g. lower bound = average / 2 and upper bound = average * 5)
Then i created a new word list with upper and lower bound.
With theese i got theese result :
Before normalization word vector length : 11880
Mean : 19 lower bound : 9 upper bound : 95
After normalization word vector length : 1595
And also cosine similarity results were better.

Python: function, for loop, error message

I am pretty new to Python and am practicing with codeacademy, am getting a strange error message with below function. I dont understand as it looks logically and syntactically correct to me, can anyone see the issue?
def compute_bill(food):
total = 0
for item in food:
total = total + item
return total
Oops, try again.
compute_bill(['apple'])
resulted in a
TypeError: unsupported operand type(s) for +: 'int' and 'str'
You cannot add a string with an integer .
typeError on python Docs -typeError
call the function like below-
compute_bill([1])
compute_bill([10,20,30])
OR
apple = 10
orange = 20
compute_bill([apple,orange])
as #Rilwan said in his answer yo cannot add string with an interger. Since you are working on codeacademy, i have completed similar assignment, I believe you have to get the cost of the food that you send to the function from a dictionary and then calculate the total.
food_cost = { "apples" : 20, "oranges" : 40}
def compute_bill(food):
total = 0
for item in food:
total = total + food_cost[item]
return total
compute_bill(['apples'])

How do I take already calculated totals that are in a loop and add them together?

I created this program in Python 2.7.3
I did this in my Computer Science class. He assigned it in two parts. For the first part we had to create a program to calculate a monthly cell phone bill for five customers. The user inputs the number of texts, minutes, and data used. Additionaly, there are overage fees. $10 for every GB of data over the limit, $.4, per minute over the limit, and $.2 per text sent over the limit. 500 is the limit amount of text messages, 750 is the limit amount of minutes, and 2 GB is the limit amount of data for the plan.
For part 2 of the assignment. I have to calculate the total tax collected, total charges (each customer bill added together), total goverment fees collected, total customers who had overages etc.
Right now all I want help on is adding the customer bills all together. As I said earlier, when you run the program it prints the Total bill for 5 customers. I don't know how to assign those seperate totals to a variable, add them together, and then eventually print them as one big variable.
TotalBill = 0
monthly_charge = 69.99
data_plan = 30
minute = 0
tax = 1.08
govfees = 9.12
Finaltext = 0
Finalminute = 0
Finaldata = 0
Finaltax = 0
TotalCust_ovrtext = 0
TotalCust_ovrminute = 0
TotalCust_ovrdata = 0
TotalCharges = 0
for i in range (1,6):
print "Calculate your cell phone bill for this month"
text = input ("Enter texts sent/received ")
minute = input ("Enter minute's used ")
data = input ("Enter Data used ")
if data > 2:
data = (data-2)*10
TotalCust_ovrdata = TotalCust_ovrdata + 1
elif data <=2:
data = 0
if minute > 750:
minute = (minute-750)*.4
TotalCust_ovrminute = TotalCust_ovrminute + 1
elif minute <=750:
minute = 0
if text > 500:
text = (text-500)*.2
TotalCust_ovrtext = TotalCust_ovrtext + 1
elif text <=500:
text = 0
TotalBill = ((monthly_charge + data_plan + text + minute + data) * (tax)) + govfees
print ("Your Total Bill is... " + str(round(TotalBill,2)))
print "The toatal number of Customer's who went over their minute's usage limit is... " ,TotalCust_ovrminute
print "The total number of Customer's who went over their texting limit is... " ,TotalCust_ovrtext
print "The total number of Customer's who went over their data limit is... " ,TotalCust_ovrdata
Some of the variables created are not used in the program. Please overlook them.
As Preet suggested.
create another variable like TotalBill i.e.
AccumulatedBill = 0
Then at the end of your loop put.
AccumulatedBill += TotalBill
This will add each TotalBill to Accumulated. Then simply print out the result at the end.
print "Total for all customers is: %s" %(AccumulatedBill)
Note: you don't normally use uppercase on variables for the first letter of the word. Use either camelCase or underscore_separated.