I have a trouble in define my own Find function - recursion

Here is my code, I try to do recursion to make a list of position but it return None or Error. I tried to fixed it by adding index but when it is recursive, it have Error: positional argument follows keyword argument.
def myfind(text,key,start=0, index=None):
if index is None:
index=[]
else:
i=0
j=start
check=0
while i<len(key) and j<len(text):
if key[i]==text[j]:
i+=1
j+=1
check+=1
else:
i=0
j+=1
check=0
if check==len(key):
# print(j-len(key),'->',j-1,sep='')
index.append(j-len(key))
myfind(text,key,start=j, index)
if j==len(text) and len(index)>0:
return {'index':index,'check':True}
else:
# print('not found')
return {'check':False}
s='i love you so, so you can love me, whenever you want so'
print(myfind(s,'so'))

Related

Confusion about recursion for BST

Is there an easy way to understand when you can just call the recursive method vs having to set that recursive method to a variable?
For example...
Just calling the recursive function to traverse:
self.recurse(node.left)
self.recurse(node.right)
Having to set the recursive function to node.left and node.right:
node.left = self.recurse(node.left)
node.right = self.recurse(node.left)
Another example is to delete a node in a bst you have to set the recursive function to root.left and root.right... I get it but not completely... is there a easy way to understand when you can just call the recursive function vs having to set it to node.left, node.right..etc...?
def deleteNode(self, root: TreeNode, key:int) -> TreeNode:
if not root:
return root
if key < root.val:
root.left = self.deleteNode(root.left,key)
elif key > root.val:
root.right = self.deleteNode(root.right,key)
else:
if not root.left:
return root.right
elif not root.right:
return root.left
root.val = self.successor(root.right)
root.right = self.deleteNode(root.right,root.val)
return root
To understand this two above scenarios (Simple Recursive Call and Set result of Recursive call to a Variable), just try to understand the following code/function.
Let's say, you have a TREE, which contains a value in every node where value is either negative or positive. Now let's say, you are going to count how many nodes are there whose value is Positive.
The TREE structure for this problem is like following:
TREE{
Integer val;
TREE left = right = null;
}
Now you gave me this problem to solve. And I wrote a function/method which will count nodes with positive value. The function is following:
Integer countNodes(TREE node){
if(node == null){
return 0;
}else{
Integer count = 0; // which will count how many nodes are there with positive value
if(node.val >= 0){
count += 1; // if the value is positive I incremented count
}
// and we are checking every other nodes present in the TREE
getCount(node.left);
getCount(node.right);
// and return the final result
return count;
}
}
Now I returned my function to you, and you executed! But what! There is a big WRONG! It's giving wrong result, over and over again!!
But why???
Let's analysis.
if(node.val >= 0){
count += 1;
}
Up to that we were right! But the problem was, we were incremented the count, but wasn't use it! Each time we was calling function recursively, a new stack frame was created, a new variable named "count" was created, but we were not using this value!
To use the variable "count", we need to re-initialize the returned value of every recursive call to the variable, that's the way we can keep a link between the current stack-frame and the previous stack-frame and the previous of previous stack-frame and goes onn!.. we need to change little-bit in the function countNodes like following:
if(node.val >= 0){
count += 1;
}
count += getCount(node.left); // re-initialize count in each recursive call
count += getCount(node.right); // re-initialize count in each recursive call
return count;
Now everything we'll be alright! this code will work perfectly!
The above scenarios is implies your problem.
self.recurse(node.left)
self.recurse(node.right)
this is nothing but simple traversing over all the nodes.
But if you need to use the returned result of every recursion, you need to initialize/re-initialize the returned value to a variable. That's what is happening with:
node.left = self.recurse(node.left)
node.right = self.recurse(node.left)
I HOPE this long (bit long) explanation will help to go further. Happy Coding! : )

Why is this recursion function parameter nil?

walk is a recursive function that walks the given tree and if walked over a file do something with it.
The "do something with it" should be changed.
I could use coroutine.yield(f) in walk but I wanted to know my mistake first.
As you see the argument lootfunc is given by a reference and should be called within walk.
But it gives me the error seen below. So why is the parameter lootfunc nil?
local KEYWORDS = {
"%.db[x]?",
"%.ojsn",
}
local function loot(d)
if MATCH == "path" then -- only look to the path not to the content
for i,keyword in pairs(KEYWORDS) do
if string.find(d,keyword) then
--coroutine.yield(d)
print(d)
end
end
end
end
local function walk (path,lootfunc)
for file in lfs.dir(path) do
if file ~= "." and file ~= ".." then
local f = path..'/'..file
local attr = lfs.attributes (f)
if(type(attr) == "table") then
if attr.mode == "directory" then
walk (f) -- next round
elseif attr.mode == "file" then
lootfunc(f)
end
end
end
end
end
walk("/path/",loot)
shadowed.lua:73: attempt to call local 'lootfunc' (a nil value)
stack traceback:
(command line):1: in function 'lootfunc'
shadowed.lua:73: in function 'walk'
shadowed.lua:71: in function 'walk'
shadowed.lua:71: in function 'walk'
shadowed.lua:88: in main chunk
[C]: in function 'dofile'
(command line):1: in function <(command line):1>
[C]: in function 'xpcall'
(command line):1: in main chunk
[C]: ?
You are calling walk(f) in the function walk, there's only one argument, the second argument is filled with nil, so change:
if attr.mode == "directory" then
walk(f) -- next round
to
if attr.mode == "directory" then
walk(f, lootfunc) -- next round

graphviz: node with edge to itself returns nullptr

i am playing with CFGs and at one point i have a graph that has an edge to itself. IE it's a do-while loop.
loop:
...
ifeq ... goto loop;
Why, if i pass the same Agnode_t pointer to the agedge() as both head and tail, does the function simply fail and return a nullptr?
example code:
Agnode_t* n = ...;
Agedge_t* e = agedge(graph, n, n);
//e == null
edit: i am talking about the c-api. also corrected the function name.

how to restrict the print values inside groovy each closure?

in groovy loop like :
x = [1,2,3,4,5]
x.each { i ->
// other CRUD type functionality - required
// print each values - not required
}
Can I restrict the print values inside the each clause. Actually I want the CRUD functionality to execute. But after that print i prints each values which I don't want.
my output as of now :
1
2
3
4
5
6
==>1
==>2
==>3
==>4
==>5
==>6
Or, use findAll to just then work on a list of interest:
[1,2,3,4,5].findAll { it % 2 == 0 }.each { println it }
Will just print the even numbers for example
Edit
Hang on, do you mean in the groovy console where it shows you the return value of the script in inverse type?
each returns the list it worked on, so you'll see the list after execution.
You can stop this by putting null at the end of your script (or something that returns null such as println "done")
Use a return statement in the end of the script.
x = [1,2,3,4,5]
x.each{println it}
return
Return from the closure to skip elements:
def list = [1, 2, 3, 4, 5, 6]
list.each { i ->
// skip uneven values
if (!(i % 2 == 0)) return
println i
}
Not that the return just skips the iteration step and does not return from the function the code is executed in.

Converting a bunch of nested recursive functions to iterative funcs

I have read that it is in principle possible to convert a recursive function to an iterative function. I have some bunch of functions calling each other. I constructed the structure of the code looking at my flowchart and it was kind of obvious to do it by recursive style. It runs good for small size problems but gives segmentation fault for bigger scale. So I am trying to switch to iterative style but I cannot imagine a way to do it technically since the branching structure confuses me. Can someone give me a clue to handle it? The code is something like that in python:
def main_function(parameters):
if condition0:
....
if condition1:
....
if condition2:
....
return function1(parameters)
else:
....
return function2(parameters)
else:
return function1(parameters)
else:
return function2(parameters)
#############################################
def function1(parameters):
if condition3:
...
return function3(parameters) ### yet another function.. so messed up? :-(((
else:
return main_function(parameters)
##############################################
def function2(parameters):
if condition4:
...
return main_function(parameters)
else:
return function1(parameters)
###############################################
def function3(parameters):
if condition5
if condition6:
...
return function3(parameters)
else:
...
return main_function(parameters)
else:
return RESULTS # The only way out!
Any idea would be greatly appreciated, thank you very much in advance.
Since every return statement that you've shown is essentially a return some_other_function(), it seems that a state machine would be a natural way to model this. There would be a state corresponding to each function, and the return statements would become state transitions.
Since every recursive call is initiated in return statements. You don't need to hold up the old stack. For example, when function1() calls return function3(), function1 stack can be removed. This way you won't get RuntimeError: maximum recursion depth exceeded.
You can achieve this by returning the successive function to call with parameters, instead of calling recursively.
def main_function(parameters):
if condition0:
if condition1:
if condition2:
return function1, parameters # return function to call next with arguments
else:
....
return function2, parameters
else:
return function1, parameters
else:
return function2, parameters
You should change the other functions to a similar way. Now you can call the main_function() as follows:
next_function, next_fun_param = main_function(parameters)
while hasattr(next_function, '__call__')
next_function, next_fun_param = next_function(next_fun_param)
# got the RESULT

Resources