The solution always returns x=0 - python

On using this code I get the value returned 0 always
def fi(arr,mini):
print(arr)
if(len(arr)<3):
x = mini
return
for j in range(1,(math.ceil(len(arr)/2) )):
l1 = 2*j+1
if(med(arr[0:l1])<mini):
mini= med(arr[0:l1])
print("hello", mini)
fi(arr[1:],mini)
return x

You define x only if len(arr) < 3. In other cases it is unassigned. You should add a default value before the if block, or within an else block depending on what you are trying to do.

You haven't declared x before assigning it to mini. What should your function return by default?

you define local variable 'x' whose scope is limited to if block and you are trying to return this variable from the function, so it's getting undefined. Better define local variable x in the function and give it some default value which should be return by the function.
def fi(arr,mini):
x = some_default_value
print(arr)
if(len(arr)<3):
x = mini
return
for j in range(1,(math.ceil(len(arr)/2) )):
l1 = 2*j+1
if(med(arr[0:l1])<mini):
mini= med(arr[0:l1])
print("hello", mini)
fi(arr[1:],mini)
return x

Related

How to create functions in python such that they return x as a variable? (interpolation)

How to create a functinon in Python such that for example:
n = int(input("number of knots: "))
xsolmed=[]
for i in range(n+1):
xsolmed.append(-1+(2*i/n))
def x(x):
return x
lni=[]
formula=1
for i in range(n+1):
for j in range(n+1):
if i==j:
pass
formula = (x(x)-xsolmed[i])/(xsolmed[j]-xsolmed[i])*formula
I think I need it to return the function such that the formula variable is a function by x in its own right and so later i can call upon it in the fashion
formula(10)=output
Set the results of a function call equal to your desired variable.
def f(x):
"A function that changes nothing"
return x
a = f(5) # same as a = 5
To avoid confusion, I recommend that you don't give functions the same name as their arguments, (i.e., don't do def x(x): ...).
If you want formula to be a function, then declare it as one, after which the correct syntax would be output = formula(10).
formula(10) is instance of a function and hence only has a value not a variable name to assign to.
A good way to write above code will be:
n = int(input("number of knots: "))
xsolmed=[]
for i in range(n+1):
xsolmed.append(-1+(2*i/n))
def y(x):
return x
def formula_calc(X):
formula=1
for i in range(n+1):
for j in range(n+1):
if i==j:
pass
formula = (X-xsolmed[i])/(xsolmed[j]-xsolmed[i])*formula
return formula
# now formula is a function of x. X can itself be a function.
print(formula(y(7))
# this will print value of formula at 7 as x(7) is 7.

int(input()) error - NameError: name '…' is not defined

I am getting an error when I try to run this simple python script:
def ask_x():
x = int(input('What is X?'))
def ask_y():
y = int(input('What is Y?'))
def result():
print(z)
def count():
if (x>10):
z = x + y
else:
z = 0
print('nono')
#start of program
ask_x()
ask_y()
count()
result()
I am using Python 3. I tried searching the forum and found Stackoverflow - input() error - NameError: name '…' is not defined
but it doesn't work for me.
This is because your variables are in a local scope. You can't access x outside of the ask_x() function.
I would suggest you read up on functions to get a better grasp of this.
def ask_x():
return int(input('What is X?'))
def ask_y():
return int(input('What is Y?'))
def result(z):
print(z)
def count(x, y):
if (x>10):
return x + y
else:
print('nono')
return 0
#start of program
x = ask_x()
y = ask_y()
z = count(x, y)
result(z)
This will grab the values in each function, however, instead of storing them in the local scope, it'll be returned to the main function and stored in the corresponding variable.
You can then send x and y as parameters to count(), take care of your logic, and return the the value to be stored as z.
I hope this makes sense!
One way to get around scoping is to return the variable you need from your function and pass it in where needed. I prefer this to using global variables:
def ask_x():
return int(input('What is X?'))
def ask_y():
return int(input('What is Y?'))
def result(z):
print(z)
def count(x,y):
if (x>10):
z = x + y
else:
z = 0
print('nono')
return z
#start of program
x = ask_x()
y = ask_y()
z = count(x,y)
result(z)
It would be better to use one of the ways presented in How to ask user for valid input to get to your input:
def askInt(text):
"""Asks for a valid int input until succeeds."""
while True:
try:
num = int(input(text))
except ValueError:
print("Invalid. Try again.")
continue
else:
return num
x = askInt("What is X?")
y = askInt("What is Y?")
This way you pass in the changing value (the text) and both profit from the variable parsing and validation.
If you dont want to return then just initialize variable with some default values
x=0
y=0
z=0
def ask_x():
global x
x = int(input('What is X?'))
def ask_y():
global y
y = int(input('What is Y?'))
def result():
global z
print(z)
def count():
global x,y,z
if (x>10):
z = x + y
else:
z = 0
print('nono')
#start of program
ask_x()
ask_y()
count()
result()
Python follows function scoping unlike some other languages like c which follows block scoping. This implies variables defined inside a function cannot be accessed outside. unless they are defined global.
Solution to your problem:
You can either return them in your functions and store them in variables in global scope or put all the input statements inside a single function.

Want to refer to variable in the outer function's scope from an inner function being returned

So I'm making a simple program that gets 2 functions(a and k) and one integer value(b), then it gets the formal parameter in the two functions(a and k) which is "x" and applies a condition x < b then based on the condition makes a function call, either a or b. But when I run the program it gives an error that x is not defined in the global frame. I want it to get "x" from the formal parameter assigned to the functions a and b and then get the condition based on that.
Here's my code
def square(x):
return x * x
def increment(x):
return x + 1
def piecewise(a, k, b):
if x<b:
return a
else:
return k
mak = piecewise(increment,square ,3 )
print(mak(1))
I guess you want to do something like this:
def piecewise(a, k, b):
def f(x):
if x < b:
return a(x)
else:
return k(x)
return f
However, I am not sure if it is a good practice. So, I leave my answer here to see the comments and learn if there is any problem with it.

Unable to return a value from a function

I have a small piece of code to understand how to return values that can be used in other sections of the code. In the following i only want to return the variable z, or the value snooze. But it does not work. Please can someone help me to understand why this will not work?
import time
def sleepy(reps, snooze):
t = []
for x in range(reps):
x = time.time()
time.sleep(snooze)
y = time.time()
z = y - x
t.append(z)
print 'difference = ', z*1000
print 'total:', (sum(t)/reps) * 1000
return z
sleepy(10, 0.001)
print z # does not like this.
If I print snooze it also grumbles. Why is that?
z is a local variable in your sleepy() function; it is not visible outside of that function.
Your function does return the value of z; assign it:
slept = sleepy(10, 0.001)
print slept
I used a different name here to illustrate that slept is a different variable.
You should not try to print z or snooze because they have a scope that is limited to the definition of the function. When you do: sleepy(10,0.001) then the value 10 is assigned to reps and the value 0.001 is assigned to snooze.
And then the things that you want are done with these variables. In the meantime a new variable called z is created with the scope inside the definition of the function. And then this value is returned. And as soon as the last statement has been executed then all the variables that are created inside the definition are deleted.
So you must do:
a = sleepy(10,0.001)
print a
This will print the value of a which is the value that you returned from inside the function.
Also you can print z if you declare it as global, that is:
import time
def sleepy(reps, snooze):
t = []
for x in range(reps):
x = time.time()
time.sleep(snooze)
y = time.time()
global z ##notice this line has been changed.
z = y - x
t.append(z)
print 'difference = ', z*1000
print 'total:', (sum(t)/reps) * 1000
Now the value to be returned is in z and you can print it as so:
sleepy(10,0.001)
print z
When you return something from a function you are calling, the syntax is as follows:
p = sleepy(10,0.001)
print p
z and snooze are local variables to the function.
You need to assign the result of the function to a variable to have it available after the function call.
z is a local variable.when you return z it not actually returns variable z instead its
returns the value which is present in z so u need to store it in another variable and print that variable
or you can just use
print sleepy(10, 0.001)

Passing argument from Parent function to nested function Python

here is my code:
def f(x):
def g(n):
if n < 10:
x = x + 1
g(n + 1)
g(0)
When I evaluate f(0), there would be an error "x referenced before assignment".
However, when I use "print x" instead of "x = x + 1" , it will work.
It seems that in the scope of g, I can only use x as an "use occurrence" but not a "binding occurrence". I guess the problem is that f passes to g only the VALUE of x.
Am I understanding it correctly or not? If not, can someone explain why the left side of "x = x + 1" is not defined before reference?
Thanks
You are understanding it correctly. You cannot use x to assign to in a nested scope in Python 2.
In Python 3, you can still use it as a binding occurrence by marking the variable as nonlocal; this is a keyword introduced for just this usecase:
def f(x):
def g(n):
nonlocal x
if n < 10:
x = x + 1
g(n + 1)
g(0)
In python 2, you have a few work-arounds; using a mutable to avoid needing to bind it, or (ab)using a function property:
def f(x):
x = [x] # lists are mutable
def g(n):
if n < 10:
x[0] = x[0] + 1 # not assigning, but mutating (x.__setitem__(0, newvalue))
g(n + 1)
g(0)
or
def f(x):
def g(n):
if n < 10:
g.x = g.x + 1
g(n + 1)
g.x = x # attribute on the function!
g(0)
Yes, assigning to names is different than reading their values. Any names that are assigned to in a function are considered local variables of that function unless you specify otherwise.
In Python 2, the only way to "specify otherwise" is to use a global statement to allow you assign to a global variable. In Python 3, you also have the nonlocal statement to assign a value to a variable in a higher (but not necessarily global) scope.
In your example, x is in a higher but non-global scope (the function f). So there is no way to assign to x from within g in Python 2. In Python 3 you could do it with a nonlocal x statement in g.

Categories