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.
Related
Why does this python code not swap the numbers?
def swap(x, y):
'''THe swap function'''
print("INSIDE")
temp = x
x = y
y = temp
#Driver_code
x = 2
y = 3
swap(x, y)
print(x)
print(y)
In the Swap function add this one line:
global x,y;
The problem is when you are calling the swap() function it is making its own variable x and y,
not using the global variable x and y
Because the swap is inside the function.
You're swapping the values of the function parameters x and y, which are different from the x and y that are used below.
Just do this:
x, y = y, x
The swap function is not returning values
def swap(x, y):
'''THe swap function'''
print("INSIDE")
temp = x
x=y
y= temp
return x,y
#Driver_code
x = 2
y = 3
x,y=swap(x, y)
print(x)
print(y)
Here, you assign the returning values to x and y.
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.
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}")
I'm currently trying to plot a graph of iterations of a certain function in python. I have defined the function as stated below but I am unsure on how to plot the graph such that the y value is on the y axis and the iteration number is on the x axis.
So, I have tried using the plt.plot function with different values in as my x values but using logistic(4, 0.7) as the y value for the y axis.
def logistic(A, x):
y = A * x * (1 - x)
return y
But each return an error. Can anyone shed any light on this, I want to do a total of 1000 iterations.
I dont understand much what you are saying concerning x being number ofiteration while you are showing us function logistic(4, 0.7). As far as I know, iterations is integer, whole number. You cant iterate just halfly or partially
def logistic(A, x):
y = A * x * (1 - x)
return y
A = 1
x_vals = []
y_vals = []
for x in range(1,1000):
x_vals.append(x)
y_vals.append(logistic(A,x))
#plt.plot(x_vals,y_vals) # See every iteration
#plt.show()
plt.plot(x_vals,y_vals) # See all iterations at once
plt.show()
Ah, the logistic map. Are you trying to make a cobweb plot? If so, your error may be elsewhere. As others have mentioned, you should post the error message and your code, so we can better help you. However, based on what you've given us, you can use numpy.arrays to achieve your desired result.
import numpy as np
import matplotlib.pyplot as plt
start = 0
end = 1
num = 1000
# Create array of 'num' evenly spaced values between 'start' and 'end'
x = np.linspace(start, end, num)
# Initialize y array
y = np.zeros(len(x))
# Logistic function
def logistic(A, x):
y = A * x * (1 - x)
return y
# Add values to y array
for i in range(len(x)):
y[i] = logistic(4, x[i])
plt.plot(x,y)
plt.show()
However, with numpy.arrays, you can omit the for loop and just do
x = np.linspace(start, end, num)
y = logistic(4, x)
and you'll get the same result, but faster.
How can I get this to give me x = z*y/a ?
from sympy import *
x,y,a,z = symbols('x y a z')
z = a*x/y
solve(z,x) # returns 0!
# would like to get z*y/a
solve(z,x) correctly returns 0 because your code is effectively asking:
What's the value of x that would cause z to become 0?
What you really want to do (as described here) is solve a*x/y==z which can be done as follows:
from sympy import *
x,y,a,z = symbols('x y a z')
equation = a*x/y
new_eq = solve(equation - z, x) # its value is [y*z/a]
Don't assign z = a*x/y, and don't pass z to solve.
solve(expr, symbol) determines what values of symbol will make expr equal 0. If you want to figure out what value of x makes z equal a*x/y, you want z - a*x/y to equal 0:
solve(z - a*x/y, x)
You do not want to assign z = a*x/y. = means something entirely different from equality.
I think the answer to this question can be of help. Applied to your example, this gives:
>>> from sympy import *
>>> x,y,a,z = symbols('x y a z')
>>> l = z
>>> r = a*x/y
>>> solve(l-r,x)
[y*z/a]
As all the other answers points out the solution,
I would like to emphasize on the use of Eq instances here.
An Eq object represents An equal relation between two objects.
For using an Eq object, your code should look something like this:
In []: a, x, y, z = symbols('a, x, y, z')
In []: foo = Eq(z, a*x/y)
In []: solve(foo, x)
Out[]: [y*z/a]