Correctly write a one-liner mathematical expression in Python - python

I have a problem that asks me to write one line of python code to do the following:
Calculate the total cost of an item whose original price is $10. You have a 30% discount on it and have to pay 5% state tax. The shipping would cost $7.5.
Following is what I came up with:
10 - (10 * 30 / 100) + (10 - (10 * 30 / 100)) * 5 / 100 + 7.5
As you can see, I am calculating 10 less 30% twice in the above code. I could use a variable to hold 10 - (10 * 30 / 100) but as the problem statement says, I need to do it in one line. Is there a better (read pythonic) way to achieve this?
This problem is from Sam's teach yourself Python in 24 hours book, btw (sorry!).

Just use basic math operations:
print ((0.7*100)*1.05)+7.5
#81.0

int/int can lose precision. You need to divide by 100.0 or float(100) instead of just 100 to get the right result. or insert this code from __future__ import division.
In [17]: 10 - (10 * 30 / 100) + (10 - (10 * 30 / 100)) * 5 / 100 + 7.5
Out[17]: 14.5
In [19]: from __future__ import division
In [20]: 10 - (10 * 30 / 100) + (10 - (10 * 30 / 100)) * 5 / 100 + 7.5
Out[20]: 14.85

You can use variables in a one liner, but you can simplify your solution like this.
print 10 * 0.7 * 1.05 + 7.5
EDIT:
As I mentioned in my comment, The code I posted is all you need. Doing anything more complicated than that can't really be useful as more than an intellectual exercise.
For example ...
print map(lambda x: x + 7.5, map(lambda x: x*1.05, map(lambda x: x*.7, [10])))[0]

Related

Why is basic math in Java showing up as 1.4 million times slower than Python? [duplicate]

This question already has answers here:
How do I write a correct micro-benchmark in Java?
(11 answers)
Is there any simple way to benchmark Python script?
(12 answers)
Closed last month.
I was experimenting to find how different the amount of time calculations took in Java and Python; I came up with an arbitrary expression to be evaluated in both languages and then took the amount of time that elapsed during the calculation and found that the time for Java was 1454584 ns while for Python, it was either 0 or 1000 ns (I'm guessing anything less than 1000 was rounded down to 0 or too small to be detected). Is Java really this slow to do relatively basic mathematical operations, or is there some difference in the way time is measured in these languages, or am I misunderstanding something about how calculations are performed? I am finding it hard to believe that there is that large of a time difference between the two, but if it is really just because of the languages, then why?
Here is my Java code, which gave the output for time elapsed of 1454584 ns in console. The calculation in result is just a random arbitrary calculation I came up with on the spot.
double result;
long start = System.nanoTime();
result = 10 + 5 - Math.pow(9, 3) * 10 / 5 + 3 - 3 - 2 - 100 * 2 + 9000 / 50 + 0.2 * 0.9 / 3 + 1 / Math.pow(3, 2) * 6;
long time = System.nanoTime() - start;
System.out.println("Result: " + result);
System.out.println("Time elapsed: " + time + " ns.");
Here is my Python code, which gave a result of either 0 ns or 1000 ns over multiple trials.
start = time.time_ns()
result = 10 + 5 - 9 ** 3 * 10 / 5 + 3 - 3 - 2 - 100 * 2 + 9000 / 50 + 0.2 * 0.9 / 3 + 1 / 3 ** 2 * 6
finish = time.time_ns()
print("Result: ",result)
print("Time elapsed:",finish - start,"ns.")

Python Math Giving Incorrect Output [duplicate]

This question already has answers here:
Python and Powers Math
(3 answers)
Closed last year.
Python is being weird again. When I put 5 * (40 ^ 2) + 50 * 40 + 100 it returns 2310. But on a calculator its 10100. I don't know why Python is making this mistake nor how to fix it. Anyone got any ideas?
If you will write
print( 5 * 40 ** 2 + 50 * 40 + 100 )
you will get the expected result.
10100
Try this instead:
5 * (40 ** 2) + 50 * 40 + 100

How to floor numbers to whole number in python [duplicate]

This question already has answers here:
How to round a number to significant figures in Python
(26 answers)
Closed 2 years ago.
I am wondering how can I floor 1,999,999 to 1,000,000 or 2,000,108 to 2,000,000 in python?
I used math.floor() but it's just for removing decimal part.
Just do it like this:
math.floor(num / 1000000) * 1000000
e.g.:
>>> num=1999999
>>> math.floor(num / 1000000) * 1000000
1000000.0
>>> num=2000108
>>> math.floor(num / 1000000) * 1000000
2000000.0
To round down positive integer to first digit
from math import floor
def r(n):
gr = 10 ** (len(str(n))-1)
return floor(n / gr) * gr
for i in [199_999, 200_100, 2_100, 315]:
print(r(i))
Output
100000
200000
2000
300
def floor_integer(num):
l = str(num)
return int(l[0]) * pow(10, len(l) - 1)
I think that will fits your needs.
print(floor_integer(5))
# 5
print(floor_integer(133))
# 100
print(floor_integer(1543))
# 1000
print(floor_integer(488765))
# 400000
print(floor_integer(1999999))
# 1000000
print(floor_integer(2000108))
# 2000000

Rounding by modulus in python

Apologies if this was asked before, I can't seem to find an answer in regards to arbitrary multiples.
I would like a function that rounds a number by multiples.
E.g, 17.4 would be rounded in multiples of 5 to 15, where 17.6 would result in 20.
This is what I came up with:
def value_2_rounded_multiple(value, multiple=1):
return round(value / multiple) * multiple
Is this reasonable, or is there a better approach?
This is some auxiliary code for testing:
multiple = 5
shift = -0.1
val_ = (multiple / 2) + shift + 3 * multiple
print("{} becomes {}".format(val_, value_2_rounded_multiple(val_, multiple=multiple)))

Understanding factorial recursion [duplicate]

This question already has answers here:
Understanding recursion in Python
(4 answers)
Closed 3 years ago.
I'm looking over the factorial example of recursion and would just like to make sure that I'm understanding it correctly!
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
Would I be right in saying:
factorial(4) = factorial(4-1) * 4 = factorial(3-1) *3 *4 = factorial(2-1) *2 *3 *4 = factorial(1-1) *1 *2 *3 *4 = 24
because factorial(1-1) = factorial(0) which as the base case shows = 1 and then we multiply by 2, then 3 then 4.
Is that the correct way of looking at it?
Thanks in advance!
Yes it is. But since it's recursion, it works the opposite way. I once had an interviewer explain it to me like this :
Say, for fact(5) :
- fact(5) = 5 * fact(4)
- fact(4) = 4 * fact(3)
- fact(3) = 3 * fact(2)
- fact(2) = 2 * fact(1)
- fact(1) = 1 * fact(0)
- fact(0) = 1
// This is where your condition returns 1.
Now, imagine that the - sign above stands for a return. You basically return whatever is after the - sign. So from the lowest line, 1 is returned. Then, you have 1 returned in fact(1) i.e. 1 * 1. So it happens in a REVERSE cascade like :
= 120
- fact(5) = 5 * 24
- fact(4) = 4 * 6 = 24
- fact(3) = 3 * 2 = 6
- fact(2) = 2 * 1 = 2
- fact(1) = 1 * 1 = 1
- fact(0) = 1
Remember that whenever you work on recursion, everything actually works in reverse. That should really help you breaking any recursion problem down.
This is actually why tail recursion and the related optimization are so important. In memory, each of those calls is delayed and can't return until the calls above it (below in the diagram) finish and return. So a very deep recursive call can cause a stack overflow unless the compiler/interpreter optimize this by turning it into the version in the OP, such that the partial results are evaluated immediately and not delayed. Python does not perform this optimization and so you must be careful with your recursive calls.
This may be helpful
(factorial 4)
(4 * (factorial 3))
(4 * (3 * (factorial 3)))
(4 * (3 * (2 * (factorial 1))))
(4 * (3 * (2 * 1)))
(4 * (3 * 2))
(4 * 6)
(24)
Yes, the way you've described it is what is going on.
One point to note with your code, if you enter a non-integer value for n or a value of n less than 0, it looks like you will be stuck in an infinite loop.
It might be worth adding a check in your code for this:
if not isinstance(n, int):
return None
elif n < 0:
return None

Categories

Resources