Assign a function to a variable recursively - function

I've read a lot about that argument here in stackoverflow. Anyway I can't really understand what really happens to a variable when I assign a recursive function to it ! I've tried so hard using printNow() command just to undestand what happening .. but nothing , just a bunch of None !
variable = function() #variable is going to be the the return value of function() ?
#if function() is a recursive function each time of the recursive, variable
#is gonna be different ?
edit :
Added a piece of code that i can't understand ..
def permute(seq):
if len(seq)<=1:
perm=[seq]
else:
perm=[]
for i in range(len(seq)):
sub=permute(seq[:i]+seq[i+1:]) # What sub is gonna be = ?
for p in sub:
perm.append(seq[i:i+1]+p)
return perm

Related

Mysterious stackoverflow in function call?

I'm creating a Lua program and I tried to use something like inheritance, but I got a stack overflow when I called the super of the function.
function Parent()
local self = {}
self.println = function(text) print(text) end
return self
end
function Child()
local super = Parent()
local this = {}
this.println = function(text)
super.println(text) -- According to the debugger, here is the problem.
print("Child")
end
for k, v in pairs(this) do
super[k] = v
end
return this
end
local a = Child()
a.println("Hello!")
I know there are other ways to do this, but I must use this kind of "OOP". Can anyone recommend me anything?
Your problem is with the loop that makes all println functions be the same println function that redirects the call to another printnl function, which is actually the same print function, creating a loop.
for k, v in pairs(this) do
super[k] = v
end
Removing that loop will make the code work, but I am not sure if this makes it behave as you wanted.
Maybe you should take a look at lua metatables if you want to inherit methods.
That for k, v in pairs(this) do loop seems backwards to me.
You are pushing the this copies of the functions into the super table (overwriting the ones that are already there).
So you push this.println into super and then call super.println inside it and you end up calling yourself repeatedly.
Did you mean to do that the other way around? Copy the super functions into this? Or what was the point with that loop in the first place?

Converting a while loop into a function? Python

In order to condense my code I am trying to make one of my while loops into a function. I have tried numerous times and have yet to receive the same result upon compiling as I would just leaving the while loop.
Here's the while loop:
while True:
i = find_lowest_i(logs)
if i == -1:
break
print "i=", i
tpl = logs[i].pop(0)
print tpl
out.append(tpl)
print out
And here's what I have so far for my function:
def mergesort(list_of_logs):
i = find_lowest_i(logs)
out = []
while True:
if i == -1:
break
print "i=", i
tpl = logs[i].pop(0)
print tpl
out.append(tpl)
print out
return out
Thanks in advance. This place is a safe-haven for a beginner programmer.
It looks like the parameter to your function is list_of_logs and you're still using logs inside the function's body. The simplest fix is probably to rename your parameter to mergesort from list_of_logs to logs. Otherwise, looks completely correct to me.

Calling function with changing input parameters in a loop Matlab

I have caught myself in a issue, I know its not that difficult but I couldnt figure out how to implement it. I have an m file that looks like
clear;
PVinv.m_SwF=20e3
for m=1:1:70;
PVinv.m_SwF=PVinv.m_SwF+1e3;
Lmin = PVinv.InductanceDimens();
Wa_Ac = PVinv.CoreSizeModel();
PVinv.CoreSelect(Wa_Ac);
[loss_ind_core,loss_ind_copper] = PVinv.InductorLossModel(PVinv.m_L_Selected);
Total_Inductor_Loss=loss_ind_core+loss_ind_copper
plot(PVinv.m_SwF,Total_Inductor_Loss,'--gs');
hold on
xlim([10e3 90e3])
set(gca,'XTickLabel',{'10';'20';'30';'40';'50';'60';'70';'80';'90'})
grid on
xlabel('Switching Frequency [kHz]');
ylabel('Power loss [W]');
end
And the function that is of interest is CoreSelect(Wa_Ac)
function obj = CoreSelect(obj, WaAc)
obj.m_Core_Available= obj.m_Core_List(i);
obj.m_L_Selected.m_Core = obj.m_Core_Available;
end
I want to change the value of i from obj.m_Core_List(1) to obj.m_Core_List(27) within that for loop of main m file. How can I get the value of the function coreselect when I call it in main m file
For eg for m=1 to 70 I want the function to take the value of i=1 then execute till plot command and then same with but i=2 and so on
Any suggestion would be really helpful
I'm not sure I understand your question perfectly, but I think you want to pass an index i to the CoreSelect function, and loop i from 1 to 27 outside of the function. Try this:
function obj = CoreSelect(obj, WaAc, i)
...
end
for i=1:27,
PVInv.CoreSelect(WaAc,i);
end

Lua - How do I use a function from another script?

I've been looking around and I have not been able to find anything that has worked for me. I'm starting to learn more Lua and to start off I'm making a simple calculator. I was able to get each individual operation onto separate programs, but when I try to combine them I just can't get it to work. My script as it is now is
require "io"
require "operations.lua"
do
print ("Please enter the first number in your problem.")
x = io.read()
print ("Please enter the second number in your problem.")
y = io.read()
print ("Please choose the operation you wish to perform.")
print ("Use 1 for addition, 2 for subtraction, 3 for multiplication, and 4 for division.")
op = io.read()
op = 1 then
function addition
op = 2 then
function subtraction
op = 3 then
function multiplication
op = 4 then
function division
print (answer)
io.read()
end
and my operations.lua script is
function addition
return answer = x+y
end
function subtraction
return answer = x-y
end
function multiplication
return answer = x*y
end
function division
return answer = x/y
end
I've tried using
if op = 1 then
answer = x+y
print(answer)
if op = 2 then
answer = x-y
print(answer)
and I did that completing each operation. But it doesn't work. I can't even get the error code that it's returning because it closes so fast. What should I do?
In your example, make these changes: You require operations.lua without the extension. Include parameters in your operations function definitions. Return the operation expression directly versus returning a statement like answer = x+y.
All together:
Code for operations.lua
function addition(x,y)
return x + y
end
--more functions go here...
function division(x,y)
return x / y
end
Code for your hosting Lua script:
require "operations"
result = addition(5,7)
print(result)
result = division(9,3)
print(result)
Once you get that working, try re-adding your io logic.
Keep in mind that as it's coded, your functions will be defined globally. To avoid polluting the global table, consider defining operations.lua as a module. Take a look at the lua-users.org Modules Tutorial.
The right if-then-else syntax:
if op==1 then
answer = a+b
elseif op==2 then
answer = a*b
end
print(answer)
After: please check the correct function-declaration syntax.
After: return answer=x+y is incorrect. If you want set answer's value, set without return. If you want return the sum, please use return x+y.
And I think you should check Programming in Lua.
First of all, learn to use the command line so you can see the errors (on Windows that would be cmd.exe).
Second, change the second line to require("operations"). The way you did it the interpreter expects a directory operations with an underlying script lua.lua.

Matlab: Abort function call with Strg+C but KEEP return value

I have a function in matlab with something like this:
function [ out ] = myFunc(arg1, arg2)
times = [];
for i = 1:arg1
tic
% do some long calculations
times = [times; toc];
end
% Return
out = times;
end
I want to abort the running function now but keep the values of times which are currently already taken. How to do it? When I press strg+c, I simply loose it because it's only a local function variable which is deleted when the function leaves the scope...
Thanks!
Simplest solution would be to turn it from a function to a script, where times would no longer be a local variable.
The more elegant solution would be to save the times variable to a .mat file within the loop. Depending on the time per iteration, you could do this on every loop, or once every ten loops, etc.
Couldn't you use persistent variables to solve your problem, e.g.
function [ out ] = myFunc(arg1, arg2)
persistent times
if nargin == 0
out = times;
return;
end;
times = [];
for i = 1:arg1
tic
% do some long calculations
times = [times; toc];
end
% Return
out = times;
end
I'm not sure whether persistent variables are cleared upon Ctrl-C, but I don't think it should be the case. What this should do: if you supply arguments, it will run as before. When you omit all arguments however, the last value of times should be returned.
onCleanup functions still fire in the presence of CTRL-C, however I don't think that's really going to help because it will be hard for you to connect the value you want to the onCleanup function handle (there are some tricky variable lifetime issues here). You may have more luck using a MATLAB handle object to track your value. For example
x = containers.Map(); x('Value') = [];
myFcn(x); % updates x('Value')
% CTRL-C
x('Value') % contains latest value
Another possible solution is to use the assignin function to send the data to your workspace on each iteration. e.g.
function [ out ] = myFunc(arg1, arg2)
times = [];
for i = 1:arg1
tic
% do some long calculations
times = [times; toc];
% copy the variable to the base workspace
assignin('base', 'thelasttimes', times)
end
% Return
out = times;
end