Alternative to conditionals (if) - python-3.x

I'm having difficulties with this task in python 3.7:
"Define a function that given two integers, a and b, returns the value of their sum. However, if the difference of a and b is an even number, the value of the sum is doubled, on the other hand, if the difference is an odd number, the value of the product of a and b gets added to the value of the sum.
For now, do not use conditionals (if)."
I don't know how to do it without using if statements. I would be thankful if anyone could help me.
If a=2 and b=2, the output should be 8.
If a=1 and b=4, the output should be 9.

To determine if the sum of the two integers is even, we use the modulo operator. The following will only evaluate to 0 or 1: (a - b) % 2. 0 = even, 1 = odd.
Knowing this, we can use this value to index into a list which contains 2 functions.
At index 0 we have the double function, which will be called when the value is even, and at index 1 we have the add_product function, called when it's odd.
def process_numbers(a, b):
def double(c):
c *= 2
return c
def add_product(c):
c += a * b
return c
functions = [double, add_product]
c = a + b
c = functions[(a - b) % 2](c)
print(c)
return c
Here is another solution using anonymous (lambda) functions, and taking advantage of the fact that c & 1 will always evaluate to 0 if the difference between a and b is even, and 1 if it's odd.
def process_numbers(a, b):
functions = (lambda: c*2, lambda: c + a*b)
c = a + b
return functions[c & 1]()
And a one-line monstrosity (avert your eyes!):
>>> (lambda a, b: (lambda: (a + b) * 2, lambda: a + b + a * b)[a + b & 1]())(1, 4)
9
>>> (lambda a, b: (lambda: (a + b) * 2, lambda: a + b + a * b)[a + b & 1]())(2, 2)
8
It's a nice little puzzle. Where did you come across it?
Another solution, based off Demi-Lune's functionless solution.
>>> a, b = 2, 2
>>> (a + b & 1)*(a + b + a*b) + (1 - a + b & 1)*(a + b)*2
8
>>> a, b = 1, 4
>>> (a + b & 1)*(a + b + a*b) + (1 - a + b & 1)*(a + b)*2
9
If the sum of a and b is even, the left half evaluates to 0, and the right half evaluates to the sum being doubled.
If the sum of a and b is odd, the right half evaluates to 0, and the left half evaluates to the sum plus the product.

Related

python finding the greatest common divisor of two numbers program

I am a new Python learner. I am trying to finding the greatest common divisor of two numbers (a =1071 and b = 462 for example). I have written two programs for this. the first one is working but the second one gives the wrong answer. what is the problem with my program??
# first program (works)
a, b = 1071, 462
while b:
a, b = b, a % b
print(a)
# second program (doesn't work truly)
a = 1071
b = 462
while b:
a = b
b = a % b
print(a)
Explanation:
Yes, HSK is right. In the 2nd loop:
while b:
a = b
b = a % b
print(a)
First a is changed to b and then what you do is b = b% b. But here:
a, b = b, a % b
it is executed as one-line so a is still a.
Solution:
So just add a third variable:
a = 1071
b = 462
while b:
c = a
a = b
b = c % b
print(c)
One thing that distinguishes Python from other programming languages is that it is interpreted rather than compiled. This means that it is executed line by line.
The second doesn't work because, for the calculation of b, you need to use the old a, not the new a that got generated on the line before (this is actually set to b so you will get b % b, which will generally be zero). The equivalent to the first loop would be:
while b:
oldA = a
a = b
b = oldA % b
print(a)
The tuple assignment in Python can be considered an atomic operation where all the values on the right side are loaded up, then assigned to all the variables on the left side.
def divisor(n):
if n ==1 or n ==2 or n ==3:
return []
else:
result=[]
aux=2
while aux <= n:
if n % aux == 0:
result.append(aux)
aux=aux+1
return result
def func (m,n):
div1=divisor(m)
div2=divisor(n)
result =[]
for x in div1:
for y in div2:
if x == y:
result.append(x)
return result
print(func (x,y))

Different syntax, different result

I'm trying an ultra simple novice exercise.
The objective of the exercise was to create a fibonacci pattern, I tried two methods that I thought were going to give the same result. But fires some reason they don't, I can't understand why.
Any ideas?
CODE 1
a = 0
b = 1
while b < 100:
print(b)
a = b
b = a + b
CODE 2:
a, b = 0, 1
while b < 100:
print(b)
a, b = b, a + b
In "CODE 1", a = b makes the next line equivalent to b = b + b, which is not correct.
In "CODE 2", a,b=b,a+b is essentially new_a = old_b; new_b = old_a + old_b. The new values are computed from the old values, then the new values are assigned to the variables. This computes the fibonacci series correctly.
To do it correctly in "CODE 1" a temporary variable is needed:
t = a
a = b
b = t + b # use original a saved in t to compute b
a,b=b,a+b eliminates the need for the temporary variable.

Interest calculator on Python

I know that this has been asked already, but I'm having trouble with how I should implement this so I'm asking here.
My python code so far is:
def calculate():
p = 10000 # dollars
n = 12 # months
r = 8 # interest %
t = float(raw_input("Type the number of year that the money will be compounded for:"))
b = p * r
a = b ** t
print(a)
calculate()
Math formula
Like John Coleman mentioned in the comments you didn't implement the formula at all.
In your code you just multiplied p with r and b to the power of t.
The right formula looks like this: p*(1+(r/n))**(n*t).
I would recommend you to read an article related to python basic operators you can find one on Python Course.
def calculate():
p = 10000
n = 12
r = .08
t = float(input("Type the number of year that the money will be compounded for:"))
formula = p*(1+(r/n))**(n*t)
return formula
print (calculate())
So you need to return a value since you are writing a function. I would say input all your values into the function directly like so:
def calculate(P, r, n , t):
exponent = n*t
parends = 1 + (r/n)
val = parends ** exponent
ans = P * val
return ans
print(calculate(10000, .08, 12, 1))
I would check out other resources to learn how to use functions. Codeacademy is a good one.
Here is the function just not broken into pieces:
def shorter(P, r, n, t):
return P*(1+(r/n))**(n*t)
print(shorter(10000, .08, 12, 1))

How to append float to list?

I want to append float to list, but I got an error like this:
<ipython-input-47-08d9c3f8f180> in maxEs()
12 Es = lists[0]*0.3862 + lists[1]*0.3091 + lists[2]*0.4884
13 aaa = []
---> 14 Es.append(aaa)
15
AttributeError: 'float' object has no attribute 'append'
I guess I can't append float to list. Can I add floats to list another way?
This is my code:
import math
def maxEs():
for a in range(1, 101):
for b in range(1,101):
for c in range(1,101):
if a+b+c == 100 :
lists = []
lists.append(a*0.01)
lists.append(b*0.01)
lists.append(c*0.01)
Es = lists[0]*0.3862 + lists[1]*0.3091 + lists[2]*0.4884
aaa = []
Es.append(aaa)
I don't know what you want, but you are trying to append a list to a float not the other way round.
Should be
aaa.append(Es)
The other answer already explained the main problem with your code, but there is more:
as already said, it has to be aaa.append(Es) (you did it right for the other list)
speaking of the other list: you don't need it at all; just use the values directly in the formula
aaa is re-initialized and overwritten in each iteration of the loop; you should probably move it to the top
you do not need the inner loop to find c; once you know a and b, you can calculate c so that it satisfies the condition
you can also restrict the loop for b, so the result does not exceed 100
finally, you should probably return some result (the max of aaa maybe?)
We do not know what exactly the code is trying to achieve, but maybe try this:
def maxEs():
aaa = []
for a in range(1, 98 + 1):
for b in range(1, 99-a + 1):
c = 100 - a - b
Es = 0.01 * (a * 0.3862 + b * 0.3091 + c * 0.4884)
aaa.append(Es)
return max(aaa)

Pythagorean triplets using python's list comprehension

I can find out Pythagorean triplets using for loop as follows:
def triplet(n): # Find all the Pythagorean triplets between 1 and n (inclusive)
for a in range(n+1):
for b in range(a):
for c in range(b):
if a*a == b*b + c*c:
print(a, b, c)
I wanted to replace this with a one-liner using list comprehension and tried the following piece:
[a, b, c in range(n+1), range(a), range(b) if a*a == b*b + c*c]
But, I get a syntax error on the closing square bracket. I tried to change the list into tuple using simple brackets, but with no success. May I know how to get it right?
I think you mean
[(a,b,c) for a in range(n+1) for b in range(a) for c in range(b) if a*a == b*b + c*c]
That at least is syntactically valid.
Notice: This solution is only for the problem when a + b + c <= N
Asssume that a<=b<=c, this version is a little faster:
triplet = [(a,b,c) for a in range(1,N//3+1) for b in range(a,N//2+1) for c in range(b,N-1) if a**2 + b**2 == c**2]

Resources