How To get factor of two numbers in python? [duplicate] - python

This question already has answers here:
Does Python have a ternary conditional operator?
(31 answers)
Closed 3 years ago.
def gcd(x, y):
(x, y) = (y, x) if x > y else (x, y)
for factor in range(x, 0, -1):
if x % factor == 0 and y % factor == 0:
return factor
What is the use of the code:
(x, y) = (y, x) if x > y else (x, y)
Isn’t it enough to get the factor through the rest of the code? I have tried to get rid of the first line and the code went wrong, but I still can’t understand it.

This insurances that the resulting x is always smaller then y.

Related

Find 3 of the lowest common multiples of 3 numbers

def mult_comun(x, y, z):
mult_co = []
mult = mult_com(x, y, z)
for i in range(1, 4):
mult *= i
mult_co.append(mult)
return mult_co
print(mult_comun(a, b, c))
This is the code I wrote, but I'm not sure it's working right (I don't think that the math in this case works like this. I mean, multiplying the least common multiple by 2, 3 and 4)
(this is the mult_com() function I defined earlier, used for finding the least common multiple)
def mult_com(x, y, z):
mult = (x * y* z) // (div_com(x, y, z) ** 2)
return mult
print("Cel mai mic multiplu comun este ", mult_com(a, b, c))
Ok, I found the math.lcm() function, so the mult_com() is edited now into
def mult_com(x, y, z):
mult = math.lcm(math.lcm(x, y), z)
return mult
Again, I am not saying that the mult_comun() is not working, it's just that I am not sure that that is the best / correct way of finding what I'm looking for.
There is a neat trick to finding the least common multiple (LCM). In mathematics,
LCM * HCF = Product(x, y)
We can use this idea and find the LCM.
# Function to find HCF the Using the Euclidian algorithm is as follows
def compute_hcf(x, y):
while(y):
x, y = y, x % y
return x
Now, taking the product of numbers and dividing it by its HCF would give you the LCM;
def compute_lcm(a, b):
return a * b / compute_hcf(a, b)

What does this expression do: (x, y) = (y, x % y)? [duplicate]

This question already has answers here:
Multiple assignment and evaluation order in Python
(11 answers)
Closed 1 year ago.
I see below code but do not know what does it do.
(x, y) = (y, x % y)
At the beginning I thought it does below:
x=y
y=x%y
But I noticed I am not right.
Can someone explain what (x, y) = (y, x % y) does?
It's called tuple assignment/unpacking, and to reproduce it linearly, you need a temporary location to store the value of x.
It is more equivalent to:
temp=x
x=y
y=temp%y
You're right, it does what you think it does. x is assigned the value of y and y is assigned the value of x%y
Example:
>>> x=5
>>> y=10
>>> (x, y) = (y, x % y)
>>> x
10
>>> y
5
>>>
x becomes 10 (i.e., the value of y)
and y becomes x%y= 5%10 =5
It does this:
t1 = y
t2 = x % y
x = t1
y = t2
del t1, t2
except that the variables t1 and t2 never actually exist. In other words, it computes the new values to assign to both x and y based on their old values, and changes both at once.
I don't have the exact terminology here.
(x, y) = (y, x % y) is doing x=y, y=x%y and the same time. If you are running this two lines in sequence, you are pass the value of y to x the do the divide.

How to assign dummy binary variables in PYOMO

Suppose I have two real variables: X & Y and two binary variables x & y.
I want to add the following constraint pyomo:
when X>0 x--->1 else x-->0
when Y>0 y--->1 else y-->0
and x+y==1
My approach was
cons1:
x>=X
cons2:
y>=Y
cons3:
x+y==1
but the above doesn't seem to work and the values of x and y are random.
Your first two conditions require big M constraints. You can try something like
M_x * x >= X, M_y * y >= Y, and x + y == 1 where M_x and M_y are be constants that you set to values that doesn't unnecessarily bound X and Y. These constraints won't restrict the values of X and Y to 1 and will make x = 1 when X > 0 and y = 1 when Y > 0.

Test whole range of possible inputs for a given question

Is there a quick way to find the maximum value (float) from a function and the corresponding arguments x, y that are both integers between 0 and 100 (inclusive)? Do I need to use the assert function or something like that to get the range of all possible inputs?
def fun_A(x,y):
import math
if x == y:
return 0
first = math.cos((y%75)*(math.pi/180))
second = math.sin((x%30)*(math.pi/180))
return (first + second) / (abs(x - y))
For small problems like this it is probably fast enough to evaluate every possible combination and choose the maximum. The numpy library makes this easy to write and pretty fast as well:
import numpy as np
def fun_A(x, y):
first = np.cos((y%75)*(np.pi/180))
second = np.sin((x%30)*(np.pi/180))
return np.where(x == y, 0, (first + second) / (abs(x - y)))
x, y = np.mgrid[0:101, 0:101]
f = fun_A(x, y)
maxindex = np.argmax(f)
print('Max =', f.flat[maxindex], ' at x =', x.flat[maxindex], 'y =', y.flat[maxindex])
Output:
Max = 1.4591796850315724 at x = 89 y = 88
Things to note:
I've just replaced calls to math with calls to np.
x and y are matrices which allow us to evaluate every possible combination the two values in one function call.
I would do this for the tan function :
from math import tan
y = 0
x = 0
for x_iteration in range(0, 101):
if tan(x_iteration) > y :
x = x_iteration
y = tan(x_iteration)
x = int(x)
y = int(y)
It's fairly straightforward to write a program to solve this:
max_result = None
max_x = 0
max_y = 0
for x in range(0, 101):
for y in range(0, 101):
result = fun_A(x, y)
if max_result is None or result > max_result:
max_result = result
max_x = x
max_y = y
print(f"x={max_x} and y={max_y} produced the maximum result of {max_result}")

Plotting Specific Regions

I am new to python. The problem is that, assume that we have two parameters, x and y, and four functions f_1, f_2, f_3 and f_4. Suppose that we know that:
If (x < 5 < y < 5+x) or (5 <= y < x) or (x= 5 and 5 < y < 10) then function f_1 is the maximum function.
If (5 < x < y < 5 + x) or (x <= y < 5) then function f_2 is the maximum function.
If (y < x < 5) or (y < 5 < x) or ( x = 5 and y < x) then function f_3 is the maximum function.
If y > x+5 then function f_4 is the maximum function.
I need to draw a plot with x-axis = x and y-axis = y which shows the regions under which each function is the maximum function.
I used the following code, however the resulted plot, shown below, is not accurate.
import numpy as np
from matplotlib import pyplot as plt
x = np.arange(0,10,.1)
y = np.arange(0,15,.2)
x,y = np.meshgrid(x,y)
maxf = np.zeros(shape = x)
maxf.fill(-9999.99)
for i in range(len(x)):
for j in range(len(y)):
if j<i<5 or j<5<i:
maxf[i,j] =1
elif i<5<=j<i+5 or 5<=j<i:
maxf[i,j] =2
elif 5<i<=j<i+5 or i<=j<5:
maxf[i,j] =3
elif i == 5 and j<5:
maxf[i,j]=1
elif i == 5 and 5<=j<10:
maxf[i,j]=2
elif j >= 5+i:
maxf[i,j]=4
plt.contourf(x,y,maxf)
plt.colorbar()
plt.show()
The result should have been sth like the following picture:
When you set the initial array to -9999.99 you now have to make sure you only contour the values that you want which is between 1-3. Since that value is so much bigger in magnitude it does not get included in your plot. Set your contour levels for your plot using this:
plt.contourf(x,y,maxf,[0,1,2,3])
Yields:
Update
I didn't notice before but you are using i,j like they are the numbers but they actually represent the indexes of the arrays which is throwing off your calculation. You need to know the index and the value so you can use enumerate. If this is still not correct, then you need to revisit your logic in your conditions.
import numpy as np
from matplotlib import pyplot as plt
y = np.arange(0,15,.01)
x = np.arange(0,10,.01)
Y,X = np.meshgrid(y,x)
maxf = np.zeros(shape = Y.shape)
maxf.fill(-9999.99)
for i,x_ in enumerate(x):
for j, y_ in enumerate(y):
if y_<x_<5 or y_<5<x_:
maxf[i,j] =3
elif x_<5<=y_<(x_+5) or 5<=y_<x_:
maxf[i,j] =1
elif 5<x_<=y_<(x_+5) or x_<=y_<5:
maxf[i,j] =2
elif x_ == 5 and y_<5:
maxf[i,j]=3
elif x_ == 5 and y_>=5:
maxf[i,j]=1
elif y_ >= (5+x_):
maxf[i,j]=4
plt.contourf(X,Y,maxf,[0,1,2,3,4])
plt.colorbar()
plt.show()
Final Note
Just because you add a condition does not mean it will get evaluated if another condition is met first. In this case your 4th function is never true because one of the other conditions is always met. If you want that condition first, then make it your first if statement. How you arrange your logical statements matters especially since you have lots of conditions and some of which overlap each other.

Categories