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'])
Related
I have a sample dataframe (df_merged_1) shown below:
The Revenue column is a float64 dtype. I want to create a new column called 'Revenue_Segment'. This is what I want the end result to look like:
Below is the code I used to segment:
if df_merged_1['Revenue'] >= 0 and df_merged_1['Revenue'] <= 2200:
df_merged_1['AUM_Segment'] == 'test1'
else:
df_merged_1['AUM_Segment'] == 'test0'
But the code is not working ... I get the following error:
TypeError: invalid type comparison
Any help is greatly appreciated!
Not elegant, but this is the only solution I can think of now:
# Make a new list to add it later to your df
rev_segment = []
# Loop through the Revenue column
for revenue in df_merged_1['Revenue']:
if revenue >= 0 and revenue <= 2200:
rev_segment.append('test1')
else:
rev_segment.append('test0')
# Now append the list to a new column
df_merged_1['Revenue_Segment'] = rev_segment
Try this:
df_merged_1['AUM_Segment'] = \
np.where((df_merged_1['Revenue']>=0) & (df_merged_1['Revenue']<=2200), 'test1', 'test2')
I used the split() function to convert string to a list time = time.split() and this is how my output looks like :
[u'1472120400.107']
[u'1472120399.999']
[u'1472120399.334']
[u'1472120397.633']
[u'1472120397.261']
[u'1472120394.328']
[u'1472120393.762']
[u'1472120393.737']
Then I tried accessing the contents of the list using print time[1] which gives the index out of range error (cause only a single value is stored in one list). I checked questions posted by other people and used print len(time). This is the output for that:
1
[u'1472120400.107']
1
[u'1472120399.999']
1
[u'1472120399.334']
1
[u'1472120397.633']
1
[u'1472120397.261']
1
[u'1472120394.328']
1
[u'1472120393.762']
1
[u'1472120393.737']
I do this entire thing inside a for loop because I get logs dynamically and have to extract out just the time.
This is part of my code:
line_collect = lines.collect() #spark function
for line in line_collect :
a = re.search(rx1,line)
time = a.group()
time = time.split()
#print time[1] #index out of range error which is why I wrote another for below
for k in time :
time1 = time[k]#trying to put those individual list values into one variable but get type error
print len(time1)
I get the following error :
time1 = time[k]
TypeError: list indices must be integers, not unicode
Can someone tell me how to read each of those single list values into just one list so I can access each of them using a single index[value]. I'm new to python.
My required output:
time =['1472120400.107','1472120399.999','1472120399.334','1472120397.633','1472120397.261','1472120394.328','1472120393.762','1472120393.737']
so that i can use time[1] to give 1472120399.999 as result.
Update: I misunderstood what you wanted. You have the correct output already and it's a string. The reason you have a u before the string is because it's a unicode string that has 16 bits. u is a python flag to distinguish it from a normal string. Printing it to the screen will give you the correct string. Use it normally as you would any other string.
time = [u'1472120400.107'] # One element just to show
for k in time:
print(k)
Looping over a list using a for loop will give you one value at a time, not the index itself. Consider using enumerate:
for k, value in enumerate(time):
time1 = value # Or time1 = time[k]
print(time1)
Or just getting the value itself:
for k in time:
time1 = k
print(time1)
--
Also, Python is zero based language, so to get the first element out of a list you probably want to use time[0].
Thanks for your help. I finally got the code right:
newlst = []
for line in line_collect :
a = re.search(rx1,line)
time = a.group()
newlst.append(float(time))
print newlst
This will put the whole list values into one list.
Output:
[1472120400.107, 1472120399.999, 1472120399.334, 1472120397.633,
1472120397.261, 1472120394.328, 1472120393.762, 1472120393.737]
So basically I have to tell the user if the staff working in a phone shop has earned a bonus. If the staff sold 4 or more phones, they get a bonus.
Problem is I keep getting this error.
if list[member_number]>=4:
TypeError: 'int' object is not subscriptable
This is my code-
How_Many_Members= int(input("Enter the number of staff members:"))
list=[]
member=1
while len(list)!= How_Many_Members:
print("how many phones did the member", member,"sold?",end=" ")
Sales=int(input(""))
list.append(Sales)
member=member+1
member_number=0
for list in range(0,How_Many_Members,1):
if list[member_number]>=4:
print("member",member_number,"has earned a bonus")
member_number=member_number+1
else:
print("member",member_number,"has not earned a bonus")
member_number=member_number+1
You have two list objects. One is an array, and the other is an object in a for statement, here:
for list in range(0,How_Many_Members,1):
You are using duplicates, and that's not good and is the thing causing your program to spit the error. It is using that list instead of the array list. And since the list in the for loop is an integer object, the error is thrown. You are basically trying to use subscript on an array but it mistakes it as the integer from the for loop because it is ambiguous. Try the following:
How_Many_Members = int(input("Enter the number of staff members:"))
list = []
member = 1
while len(list) != How_Many_Members:
print("how many phones did the member", member, "sold?", end=" ")
Sales = int(input(""))
list.append(Sales)
member += 1
member_number = 0
for _ in range(0, How_Many_Members, 1):
if list[member_number] >= 4:
print("member", member_number + 1, "has earned a bonus")
member_number += 1
else:
print("member", member_number + 1, "has not earned a bonus")
member_number += 1
Something else, you misspelled member_number in a few places and I fixed that for you. I also shorted some statements and let it print member 1 instead of member 0.
Your problem is here:
for list in range(0,How_Many_Members,1):
if list[member_number]>=4:
print("member",memeber_number,"has earned a bonus")
member_number=member_number+1
else:
print("member",memeber_number,"has not earned a bonus")
member_number=member_number+1
You are saying for list in range(0, How_Many_Members), so list is taking an integer value from 0 to How_Many_Members-1. So it's not a list anymore and you can't do list[member_number].
I know this has been asked a number of times but somehow that didn't work out. I have this model field in model Song.
sent_score = models.DecimalField(default= 0.0,max_digits=4,decimal_places=2,blank=True)
In my view i update sent score the following ways.
song_item = Song.objects.get(id=id)
com_list = Comment.objects.filter(song_id=id)
com_count = com_list.count()
pos_comments = com_list.filter(sentiment='positive')
pos_count = pos_comments.count()
getcontext().prec = 2
sent_score = Decimal(pos_count)/Decimal(com_count)
However it still gives me this error:
InvalidOperation: quantize result has too many digits for current context
I also tried the quantize method in this way:
sc = Decimal(pos_count)/Decimal(com_count)
Decimal(sc).quantize(Decimal('12.12'), rounding = ROUND_DOWN)
song_item.sent_score = sc
song_item.save()
but it still gives the same error please tell me where am i going wrong
You should not use getcontext().prec = 2 as you did in your first try, because it changes the precision for everything, not just this one calculation.
The issue with your second example is, that Decimal(sc).quantize(Decimal('12.12'), rounding=ROUND_DOWN) and even sc.quantize(Decimal('12.12'), rounding=ROUND_DOWN) do not change sc. Here is an example that works:
sc = Decimal(pos_count)/Decimal(com_count)
sc_adjusted = sc.quantize(Decimal('12.12'), rounding=ROUND_DOWN)
song_item.sent_score = sc_adjusted
song_item.save()
I am using Pandas to calculate the standard deviation of a column in a data frame then multiply it by 100 to get a percentage, and then finally print it as follows:
import pandas as pd
results = pd.read_csv("MRAret.csv")
vol = results["Return"].std
print "Volatility: ",round(vol*100,2),"%"
However I am getting the following error:
File "C:/Users/Stuart/Documents/SPYDER/MRA Analysis.py", line 37, in <module>
print "Volatility: ",round(vol*100,2),"%"
TypeError: unsupported operand type(s) for *: 'instancemethod' and 'int'
So obviously the "vol" variable type is an "instancemethod", which I have never come across before (I am new to Pandas).
I have tried changing the type to float using:
vol = float(vol)
but I get the following error:
TypeError: float() argument must be a string or a number
When I just type in "vol" into my iPython console I get the output:
In [95]: vol
-> vol()
Out[95]: 0.005856992616571794
But when I type:
print vol
I get:
In [96]: print vol
<bound method Series.std of 0 0.000000
1 0.004864
2 0.001604
...
2369 0.004290
2370 0.014001
Name: Return, dtype: float64
I don't understand how it can be one single value and an array of values at the same time.
Could someone please explain to me how I can manipulate the vol variable of "instancemethod" type, in order to carry out arithmetic calculations.
Many thanks.
Your error came from this typo:
vol = results["Return"].std
essentially vol referenced the std method you wanted to do this:
vol = results["Return"].std()
which is the output of that method