Can anyone please explain this following programming questioñ? - python

Question: Define a Python function named calculate_tax() which accepts one parameter, income, and returns the income tax. Income is taxed according to the following rule: the first $250,000 is taxed at 40% and any remaining income is taxed at 80%. For example, calculate_tax(100000) should return $100,000 * 0.40 = $40,000, while calculate_tax(300000) should return $250,000 * 0.40 + 50,000 * 0.80 = $140,000.
My question is simple, does the question ask for me to print out the whole math operation $100,000 * 0.40 = $40,000, or just the final answer$40,000?

It does say "should return $250,000 * 0.40 + 50,000 * 0.80 = $140,000," but all your function should actually return is the final value of 250000. The function should simply do the calculation and return the result. The equation is written out in order to help you create the function, not as an output requirement.
However, the best person to clarify assignments is the teacher who assigned them.

Is not it? like this:
def calculate_tax(income=250000):
tax = 0
if income <= 250000:
tax = income * 0.4
else:
tax = 250000 * 0.4 + (income - 250000) * 0.8
return int(tax)
print calculate_tax(100000) # 40000
print calculate_tax(300000) # 140000

Related

Having a hard time grasping *= function

So if
balance = int(100)
balance *= 0.05
since balance is mutable should'nt that equal to 105? instead i just get 5.
and if i add another line of code such as
balance = int(100)
balance *= 0.05
balance *= 0.05
the output would be 0.25, essentially my variable is not carrying over and im just multiplying the end outcome to 5%
if i add
balance= int(100)
balance *= 0.05 + balance
i get 10005
I thought += or *= function could be used for an equation that would take a variable, do the equation then carry over the variable + the outcome as the new variable.
How do i do that for a multi step equation.
balance = int(100)
balance *= 0.05
is the same as
balance = int(100)
balance = balance * 0.05
Wouldn't you say that that's 5, not 105?
A *= B is just a shorthand for A = A * B.
Your third example is the same as:
balance= int(100)
balance = balance * (0.05 + balance)
Again, you're getting what I would think you'd expect from this code.
BTW, you don't need the int(). 100 by itself is a literal value of type 'int'. So the most concise way to state your first code block is:
balance = 100 * .05
Sorry for saying this but you have to first under the python or any programming language basics.
'+' is addition sigh
'*' is multiplication sign
A = 2 + 3
gives 5 as answer, and
A = 2 * 3 will give 6 as answer.
Secondly, '+=' , '*=' are shorthand where the operation's first value is the same space where you want to save the result.
like
A = 5
and want to add 3 in this same 'A'
A = A + 3 or can also be written as A += 3,
similarly for multiplication
A = 100
A = 100 * 0.05 can also be written as A *= 0.05
it will give A as 5
So, good luck.

An unexpected augmented assignment discount += item.total() * .1

I am following "Fluent Python" to learn Function and Design Pattern:
In chapter 6 example-code/strategy.py
def bulk_item_promo(order):
"""10% discount for each LineItem with 20 or more units"""
discount = 0
for item in order.cart:
if item.quantity >= 20:
discount += item.total() * .1 #augmented += ?
return discount
I am very confused about:
discount += item.total() * .1
I assume it overhead complicated, because it's just
discount = item.total() * .1
However, the author prefer to state it like
discount = 0*1 + 0*2 + 0*3 + item.total() * .1
to increase it complexity artificially.
What's the key points I missed? could you please provide any hints?
The code discount += item.total() * .1 is equivalent to:
discount = discount + (item.total() * 0.1)
I've added the parentheses for clarity, but they are not necessary as multiplication has precedence over addition.
Your function calculates an absolute discount by aggregating discounts for all items with quantity greater than 20. The discount equates to 10% of the undiscounted cost of in-scope items.
The same function can also be written with sum and a generator expression:
def bulk_item_promo(order):
"""10% discount for each LineItem with 20 or more units"""
return sum(item.total() * 0.1 for item in order.cart if item.quantity >= 20)
Suppose there are 3 items in the order. Call them a, b, and c. Say that each one had more than 20 units. Say that a.total() == b.total() == c.total() == 100. In the case of:
discount = item.total() * .1
discount will be 10. So you would get 10 off the entire 300. But that isn't really what you want, you want 10 off of each a.total(), b.total() and c.total(), so you want 30. This why you use += instead as it aggregates over each (qualified) item.
Every item in the basket can have a discount. To calculate the total discount, you need to add up the individual discounts for all items that have an discount, and that is what the code does. Calling the variable "total_discount" instead of "discount" might have been better.
left += right
means: Calculate the value "right", then add it to the variable left. discount_total += (formula for item discount) means calculate the item discount according to the formula, and add it to the discount_total. In your case
discount_total += item.total() * 0.1
means: Calculate the discount for this item by calculating its total and multiplying by 0.1 (which is the same as taking ten percent). Then add the discount for this item to the discount total.

How do I use dictionary to replace long if else block?

I'm writing an income tax calculator for 2017. Right now for calculating Federal taxes I have a long if else block:
def taxes(income):
"""Calculate income tax brackets from 10% to 39.6%"""
if 0 < income <= 9325:
return income * 0.1
elif income <= 37950:
return 932.5 + .15 * (income - 9325)
elif income <= 91900:
return 5226.25 + .25 * (income - 37950)
elif income <= 191650:
return 18713.75 + .28 * (income - 91900)
elif income <= 416700:
return 46643.75 + .33 * (income - 191650)
elif income <= 418400:
return 120910.25 + .35 * (income - 416700)
else:
return 121505.25 + .396 * (income - 418400)
I found in some other posts that I can use dictionary to access the values directly with dict.get(key, default). But in my case it's a bit different since I'm comparing income in a range of tax brackets and doing calculations with the income. Is there a way for me to use dictionary to simulate the if else block?
By using lambda functions and the thresholds in your if-else statements, you could do:
TAX_DICT = {
0: lambda income: income * 0.1,
9325: lambda income: 932.5 + .15 * (income - 9325),
37950: lambda income: 5226.25 + .25 * (income - 37950),
91900: lambda income: 18713.75 + .28 * (income - 91900),
191650: lambda income: 46643.75 + .33 * (income - 191650),
416700: lambda income: 120910.25 + .35 * (income - 416700),
418400: lambda income: 121505.25 + .396 * (income - 418400)
}
def taxes(income):
for threshold in sorted(TAX_DICT)[::-1]:
if income >= threshold:
return TAX_DICT[threshold](income)
You could also create a regular function for each threshold instead of a lambda function.
Dictionaries work by taking all the possible hashcodes that values could have and dividing them up into buckets. When you want to look something up they hash it, check in the appropriate bucket, and see if there's something there.
This approach isn't going to work here, because if you look up a number like 100,000 the dictionary won't know to look under the hash value of 91,900 in particular.
What you want instead for this class of problem is a sorted collection of tuples that you can perform a binary search on. If the list is going to change at runtime this should be some kind of self-balancing binary tree; if not, it can just be a pre-sorted array.
In your case since there are only a few items, doing a binary search is probably more trouble than it's worth; just walking through the list should be fine.

TypeError: can't multiply sequence by non-int of type 'float', I can't figure out

This is that piece of code I wrote:
#This is the first ever piece of code I/'m Writing here
#This calculates the value after applying GST
#Example: here we are applying on a smartphone costing 10000
Cost = input('Enter the MRP of device here ')
Tax = 0.12
Discount = 0.05
Cost = Cost + Cost * float(Tax)
Total = Cost + Cost * float(Discount)
print(Total)
Whenever I try to execute the code it gives an exception after input:
TypeError: can't multiply sequence by non-int of type 'float'
There's a few weird parts here I'll try to break them down. The first is the one you are actually asking about which is caused by input returning a string, so you are effectively doing something like this. I'm going to lowercase the variable names to match python style
cost = "2.50"
tax = 0.12
#...
cost * tax # multiplying str and float
Fix this by wrapping the call to input with a call to float to convert the str
cost = float(input('Enter the MRP of device here '))
tax = 0.12
discount = 0.5
next you have these extra calls float(tax) and float(discount). Since both of these are floats already, you don't need this.
There is also a shorthand syntax for x = x + y which is x += y with these two things in mind, you can adjust your calculation lines:
cost += cost * tax
cost += cost * discount
print(cost)
raw input is as string,cast it into float
Cost = input('Enter the MRP of device here ')
Cost=float(Cost)
Tax = 0.12
Discount = 0.05
Cost = Cost + Cost * float(Tax)
Total = Cost + Cost * float(Discount)
print(Total)

Thinkpython book exercise

price_book = 24.95
number_books = 60.0/100
first_book_cost = 3
additional_copy = 0.75
discounted_books = price_book*number_books
total_price = discounted_books*(first_book_cost*1+additional_copy*(60-1))
print "The total price of 60 copies of book is %s$."%(total_price)
Suppose the cover price of a book is $24.95, but bookstores get a 40% discount. Shipping costs $3 for the first copy and 75 cents for each additional copy. What is the total wholesale cost for 60 copies?
Could someone please tell me what am I doing wrong!!
The answer should be 523.23, and I am getting 707.33!
Thank you in advance!
Sometimes books, especially free ones, have typos and errors.
According to the information you provided, the total wholesale cost should be:
>>> cover_price_of_book = 24.95
>>> shipping_cost_for_first_book = 3.00
>>> shipping_cost_for_additional_books = 0.75
>>> wholesale_cost_of_book = 24.95 * .60
>>> total_number_of_books = 60
>>> total_wholesale_cost = (wholesale_cost_of_book * total_number_of_books) + (shipping_cost_for_first_book + (total_number_of_books - 1) * shipping_cost_for_additional_books)
total_wholesale_cost
945.4499999999
The question here isn't very clearly stated.
Do they get a 40% discount on order total/book cost/etc.?
I modeled what I thought you were asking, but I cannot come close to 523.23.
In fact, all books being 40% discounted to 14.97 * 60, comes to 898.20 before shipping costs.
#first book costs 24.95
book_cost = 24.95
#they order 60 books
number_books = 60
#shipping cost of book 1 is $3
ship1_cost = 3
#shipping cost for subsequent books is 0.75
ship_cost = 0.75
#print (book 1 + shipping) + (subsequent book qty (59) * unit price) + (subsequent shipping costs (59 * 0.75))
print (book_cost + ship1_cost + ((number_books - 1) * book_cost) + ((number_books - 1) * ship_cost))

Categories

Resources