I'm trying to convert a big function from Matlab to Python. The function starts like this.
function net = ANN_AP(X,T,OutputName)
I used def net = ANN_AP(X,T,OutputName): but an error of syntax appears.
Any helps?
In python the values a function returns are defined when you call return rather than in the def line. So return net at the end would do what you want. This allows you to return different outputs or even different numbers of outputs depending on the scenario, something more difficult to do in MATLAB. So
function net = ANN_AP(X,T,OutputName)
do something
end
Is equivalent to:
def ANN_AP(X, T, OutputName):
do something
return net
Related
I have written the two functions below in the same python file. If I print the answer function it returns the answer of 7 which is expected.
The second function is calling the first function to get the answer.
If I create two python files as below and run it there is an error NameError: name 'math' is not defined.
Why am I not able to create the function that is required to run answer() in the second python file?
I have tried referencing math = 0 to give it a starting variable. My goal is to be able to build functions that I can import into the main python file where that function uses functions created in the main file. The two files are p1.py and p2.py
def math(x,y):
answer = x + y
return answer
def answer():
answer = math(5,2)
return answer
print(answer())
# Returns the answer of 7
def answer():
answer = math(5,2)
return answer
import p1
def math(x,y):
answer = x + y
return answer
print(answer())
# Returns NameError: name 'math' is not defined.
There are a few ways to make it work, you can make answer take a function as an argument:
def answer(math):
answer = math(5,2)
return answer
and call it with answer(math), or you could import it in p1.py by adding from p2 import math.
I am currently learning on an online learning platform, and my code has to pass the test cases(included below)
Heres the question:
Write a higher-order function exception_function which will return a function with exceptions. exception_function should take in a function f(x), an integer input, and an integer output, and return another function g(x). The output of g(x) should be the same as f(x), except that when x is the same as the integer input, the output will be returned.
For example, given that we have a function sqrt which returns the square root of the argument. Using new_sqrt = exception_function(sqrt, 7, 2) we obtain new_sqrt, which behaves similarly to sqrt except for new_sqrt(7), where the value of 2 will be returned.
Below is the answer template
from math import *
def exception_function(f, rejected_input, new_output):
"""Your code here"""
pass
#################
#DO NOT REMOVE#
#################
new_sqrt = exception_function(sqrt, 7, 2)
Test Cases:
new_sqrt(9) -expected answer 3
new_sqrt(7) -expected answer 2
Here is what im not sure about.
How to control what f will return without changing f itself?
Thank you very much for your time.
Managed to solve it!
def exception_function(f, rejected_input, new_output):
def inner_function(x):
if x==rejected_input:
return new_output
else:
return f(x)
return inner_function
new_sqrt = exception_function(sqrt, 7, 2)
The use of the command "return" has always been bothering me since I started learning Python about a month ago(completely no programming background)
The function "double()" seems working fine without me have to reassign the value of the list used as an argument for the function and the value of the elements processed by the function would double as planned. Without the need to assign it outside the function.
However, the function "only_upper()" would require me to assign the list passed as argument through the function in order to see the effect of the function. I have to specify t=only_upper(t) outside of the function to see the effect.
So my question is this: Why are these two seemingly same function produces different result from the use of return?
Please explain in terms as plain as possible due to my inadequate programming skill. Thank you for your input.
def double(x):
for i in range(len(x)):
x[i] = int(x[i])*2
return x
x = [1, 2, 3]
print double(x)
def only_upper(t):
res = []
for s in t:
if s.isupper():
res.append(s)
t = res
return t
t = ['a', 'B', 'C']
t = only_upper(t)
print t
i am assuming that this is your first programming language hence the problem with understanding the return statement found in the functions.
The return in our functions is a means for us to literally return the values we want from that given 'formula' AKA function. For example,
def calculate(x,y):
multiply = x * y
return multiply
print calculate(5,5)
the function calculate defines the steps to be executed in a chunk. Then you ask yourself what values do you want to get from that chunk of steps. In my example, my function is to calculate the multiplied value from 2 values, hence returning the multiplied value. This can be shorten to the following
def calculate(x,y):
return x * y
print calculate(5,5)
I'm trying to create a function with local functions within it. The main function would receive an output from an outside source, and the functions within it would be required to translate that input and return results for later use. My problem is that the way I am currently attempting this, when I try to put in my first local function inside the main function, I continue to get nil. Here is an example:
function stats(input)
height, weight, name, age, gender, relate = string.match(input, "(%d*)ft,(%d*)lbs,(%w*),(%d*),(%u*),(%u)")
if name then
function nameInit(relate)
relateTable = {["F"] = "Friend", ["R"] = "Relative"}
for k,v in pairs (relateTable) do
if relate == k then
relship = v
return relship
end
end
end
end
person = name.." is "..age.." years old, weighs "..weight.." and blah blah blah....
return person
end
print (stats("5.8ft, 160lbs, Mike Scott, 19, M, F"))
Obviously, this subject isn't practical but what I'm trying to do is along the same lines in terms of end response. I'm currently getting lua: filename: attempt to concatenate global 'relship' (a nil value)? I can get the response I want without the nested function. But when I try to elaborate more on the response I would like to receive, and place that function inside the global function, I begin to get these response(s). This seems to be my problem anytime I attempt to use functions within other functions. I can make two separate global functions and print results from either one. But the minute I try to use one within another, I screw myself up. Anyone who can take some time to help a beginner better understand what he is doing wrong would be great! Thanks all.
Based on your statement "the functions within it would be required to translate that input and return results for later use", I'm not sure that nested functions is what you want. You say that when you have two global functions your code works:
function func1(args)
...
end
function func2(args)
...
end
but when you nest (for example) func1 inside func2, it no longer works. Lua does allow you to define nested functions, but I can only think of two reasons to use them:
to return a function that encapsulates a task, usually with some of the wrapper function's args and/or locals as upvalues.
to encapsulate some logic in a function to be called from within the wrapper function, with no need for any other functions to call it.
For example of case 1:
function func2(a, b, c)
function func1()
do something with a, b, c eventhough they are not args of func1
return result
end
return func1
end
someFunc = func2(1,2,3)
....
result = someFunc() -- calls func1 created inside func2, using 1,2,3
For example of case 2:
function func2(a, b, c)
function func1()
do something with a, b, c eventhough they are not args of func1
return result
end
result = func1()
...
end
func2(1,2,3)
You could also add a nested function to a table object (class) passed as argument, but I see this as a variation on case 1.
I'm trying to develop a function which performs math on two values which have the same key:
property = {a=120, b=50, c=85}
operator = {has = {a, b}, coefficient = {a = 0.45}}
function Result(x) return operator.has.x * operator.coefficient.x end
print (Result(a))
error: attempt to perform arithmetic on field 'x' (a nil value)
The problem is that the function is attempting math on literally
"operator.has.x" instead of "operator.has.a".
I'm able to call a function (x) return x.something end, but if I try function (x) something.x i get an error. I need to improve my understanding of functions in Lua, but I can't find this in the manuals.
I'm not exactly sure what you're trying to do, but here is some working code that is based on your code:
property = {a=120, b=50, c=85}
operator = {has = {a=2, b=3}, coefficient = {a = 0.45}}
function Result(x) return operator.has[x] * operator.coefficient[x] end
print (Result('a'))
Prints '0.9'
This is a common gotcha for newcomers to the language. Buried in the Lua manual somewhere:
To represent records, Lua uses the field name as an index. The
language supports this representation by providing a.name as syntactic
sugar for a["name"].
This explains why your function Result(x) is failing. If you translate the syntactic sugar, your function becomes:
function Result(x)
return operator.has['x'] * operator.coefficient['x']
end
Geary already offered a solution to this so I won't reiterate it here.