I have a simple question about the logic behind this Python code - python

I'm a beginner in Python, and I'm stuck in a function code.
def max_of_two( x, y ):
if x > y:
return x
return y
def max_of_three( x, y, z ):
return max_of_two( x, max_of_two( y, z ) )
print(max_of_three(30, 25, 50))
Can someone explain to me the logic behind putting the first function (max_of_two()) inside the parameters of the second function (max_of_three())? I've seen a function inside a function code, and that's not a problem, but I've never seen a function inside the parameters of another function... I'm very confused. I know what the code does, it basically shows the greater number. The first function I understood perfectly, but the second one confused me...

x = 1
y = 2
z = 3
max_of_two( y, z )
> 3
max_of_two( x, max_of_two( y, z ) )
# is the same as
max_of_two( x, z )
# is the same as
max_of_two( x, 3 )
The result of the inner function is used as a parameter for the outer function because the inner function is evaluated first.

This is not putting a function inside parameters. First I recommend you understand parameter vs argument, here's a quote from "Parameter" vs "Argument" :
Old post, but another way of saying it: argument is the value/variable/reference being passed in, parameter is the receiving variable used w/in the function/block
def max_of_three( x, y, z ):
return max_of_two( x, max_of_two( y, z ) )
For example, (x, y, z) are parameters of max_of_three, and (y, z) are arguments passed to max_of_two
——————————————————————————————————————————
Then you should understand function calls. max_of_two( y, z ) is an example of a function call, where you call the function max_of_two, by making a function call, you get the return value corresponding to your arguments.
In this case, when you write:
max_of_two( x, max_of_two( y, z ) )
you first get the return value corresponding to (y, z) from max_of_two, and the pass x and the return value above to another max_of_two function, then you return the new return value from max_of_three. This is equivalent to:
retval = max_of_two( y, z )
retval2 = max_of_two( x, retval )
return retval2

It's like a nested if in other languages. You have three arguments to the second function. These are passed to the first function that verifies them in pairs.
If you wanted to use a single function max_of_three(x, y, z) it should look like a succession of if statements with an intermediary variable.
def max_of_three(x,y,z):
if x > y:
temp = x
else:
temp = y
if temp > z:
result = temp
else:
result = z
return result

Related

How to minimise a sum of two functions allowing one of the arguments to vary over both functions?

I have two functions f(x,y,z) and g(x,y,z). I want to minimise the sum
h(x,y,z) = f(x,y,z) + g(x,y,z), allowing x to be variable over both functions f and g.
I can minimise both these functions separately or together using scipy.optimise.minimise, which basically calculates the values of f + g (or h) at a bunch of x, y and z values, and then returns me the values (x, y, z) for which f + g is minimum.
What happens here is that : both f and g are evaluated at same values of (x, y, z), but I want one of the arguments (say x) to vary over f and g.
This is a rough outline of what I am trying:
def f(x,y,z):
return scalar
def g(x,y,z):
return another_scalar
def h(theta):
x, y, z = theta
return f(x,y,z) + g(x,y,z)
def bestfit(guess, method='Nelder-Mead'):
result = op.minimize(h,
guess,
method=method,
options={'maxfev': 5000,
'disp': False})
if not result.success:
print('Optimisation did not converge.')
return result
g = [x0, y0, z0]
bf = bestfit(g, method='Nelder-Mead')
print(bf)
I am not sure if I can do it using scipy.optimise. Can I? Or is there some other python module I can use?
My first thought would be to define new functions, say a and b, with fixed values of y and z, such that your new functions are a(x) = f(x, y0, z0) and b(x) = g(x, y0, z0) and then minimize these functions.

Why does this python code not swap the numbers?

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.

Random walk in python

I am trying to implement a random walk in python. This is the error I get. I feel my implementation is wrong or at least not the best. Can someone have a look at it. Keep in mind I am a beginner in python and this is how I think someone would code something, so I can be totally off.
in randomWalk(stepSize, stepNumber)
37 for _ in range(stepNumber):
38 r = randint(1,4)
---> 39 x,y = movement[r]
40 xList.append(x)
41 yList.append(y)
TypeError: 'function' object is not iterable
This is my code
from pylab import *
import numpy as np
import matplotlib.pyplot as plt
import random as rnd
matplotlib.rcParams.update({'font.size': 20})
x = 0.
y = 0.
xList = []
yList = []
def goRight(stepSize, y):
direction = np.cos(0)
x = stepSize*direction
return [x,y]
def goUp(stepSize, x):
direction = np.cos(90)
y = stepSize*direction
return [x,y]
def goLeft(stepSize, y):
direction = np.cos(180)
x = stepSize*direction
return [x,y]
def goDown(stepSize, x):
direction = np.cos(270)
y = stepSize*direction
return [x,y]
def randomWalk(stepSize, stepNumber):
movement = {1: goRight,
2: goUp,
3: goLeft,
4: goDown}
for _ in range(stepNumber):
r = randint(1,4)
x,y = movement[r]
xList.append(x)
yList.append(y)
plt.ioff()
plot(x, y)
plt.show()
randomWalk(1.,4)
You are putting functions in your dict movement. movement[r] is not calling the function, only accessing them. What you line is basically doing, is:
x, y = goDown
If you want to call the function in that line, you have to add parentheses and arguments, something like:
x, y = movement[r](stepSize, x)
Which shows that you have a problem in your design, since some functions expect x and some expect y. You could maybe fix that by having all the functions take both coordinates, x and y, and then your line should go like
x, y = movement[r](stepSize, x, y)
The problem is with the line
x,y = movement[r]
The dictionary movement is a list of ints to functions when you call movement[r] only a single function is returned, but here you are trying to unpack it. Instead I think you want:
x,y = movement[r](stepSize)
This will call your function and so return the coords you want.
Also you need to change all your step methods to only take the one parameter...
You can not call a function in a dictionary of fucntions like this , use this instead :
functionToCall = movement[r] # look up for function in dictionary
x,y = functionToCall(stepsize , x, y) # then call function with desired parameters

Calculate implicit integral function contours with python

I guess I am missing something in this code:
integrand = lambda t,x,y: (1/(Tiempo-t))*np.exp(-((x-U*(Tiempo-t))**2+y**2)/(4*a*(Tiempo-t)))
def z_func(x,y,Rate,Conductivity):
integral, err = integrate.quad(integrand,0,Tiempo,args=(x,y,))
return ((Rate/(2*math.pi* Conductivity))*integral)
Z = z_func(X, Y, Ql, k)
cs = plt.contour(X, Y, Z,[IncT])
I have an implicit function with an integral, something like f(x,y,t)=A*Integral, where A is constant. It integrates over t. I need to calculate the contour for an specific value of t. But I get several errors such as "Supplied function does not return a valid float", which is the actual error when evaluating the z_func.
What am I doing wrong? Is there another way to solve it?
I should add I'm working with a meshgrid:
x = arange(-1.0,10.0,0.1)
y = arange(-1.0,10.0,0.1)
X,Y = meshgrid(x, y)
Thanks in advance!
To avoid this error, z_func must be vectorized:
vz_func = np.vectorize(z_func)
Z = vz_func(X, Y, Ql, k)

How do I generate test data for my Python script?

A equation takes values in the following form :
x = [0x02,0x00] # which is later internally converted to in the called function to 0x300
y = [0x01, 0xFF]
z = [0x01, 0x0F]
How do I generate a series of test values for this function ?
for instance I want to send a 100 odd values from a for loop
for i in range(0,300):
# where a,b are derived for a range
x = [a,b]
My question was a bit unclear so please let my clarify.
what I wanted to ask how I can do x =[a,b] generate different values for a,b
use generators:
def gen_xyz( max_iteration ):
for i in xrange( 0, max_iteration ):
# code which will generate next ( x, y, z )
yield ( x, y, z )
for x, y, z in gen_xyz( 1000 ):
f( x, y, z )
The hex() function?
import random
for i in range(10):
a1, a2 = random.randint(1,100), random.randint(1,100)
x = [hex(a1), hex(a2)]
print x
..outputs something similar to..
['0x21', '0x4f']
['0x59', '0x5c']
['0x61', '0x40']
['0x57', '0x45']
['0x1a', '0x11']
['0x4c', '0x49']
['0x40', '0x1b']
['0x1f', '0x7']
['0x8', '0x2b']
['0x1e', '0x13']

Categories