Max Recursion Depth Error With Grid Search Problem - recursion

I've written out a potential solution to a Leetcode problem but I get this error involving maximum recursion depth. I'm really unsure what I'm doing wrong. Here's what I've tried writing:
def orangesRotting(grid):
R,C = len(grid), len(grid[0])
seen = set()
min_time = 0
def fresh_search(r,c, time):
if ((r,c,time) in seen or r < 0 or c < 0 or r >= R or c >= C or grid[r][c] == 0):
return
elif grid[r][c] == 2:
seen.add((r,c,0))
elif grid[r][c] == 1:
seen.add((r,c, time + 1))
fresh_search(r+1,c,time+1)
fresh_search(r-1,c,time+1)
fresh_search(r,c+1,time+1)
fresh_search(r,c-1,time+1)
for i in range(R):
for j in range(C):
if grid[i][j] == 2:
fresh_search(i,j,0)
for _,_,t in list(seen):
min_time = max(min_time,t)
return min_time
Even on a simple input like grid = [[2,1,1], [1,1,0], [0,1,1]]. The offending line always appears to be at the if statement
if ((r,c,time) in seen or r < 0 or c < 0 or r >= R or c >= C or grid[r][c] == 0):
Please note, I'm not looking for help in solving the problem, just understanding why I'm running into this massive recursion issue. For reference, here is the link to the problem. Any help would be appreciated.

So let's trace through what you are doing here. You iterate through the entire grid and if the value for that cell is 2 you call fresh_search for that cell. We'll start with [0,0]
In fresh_search you then add the cell with times seen = 0 to your set.
Now for all neighboring cells you call fresh_search so we'll just look at r+1. For r+1 your method fresh_search adds the cell to your set with times seen = 1 and then calls fresh_search again with all neighboring cells.
Next we'll just look at r-1 which is our origin and now fresh_search is being called with this cell and times seen = 2. Now this value isn't in the set yet because (0,0,0) != (0,0,2) so it adds it to the set and again calls fresh_search with the r+1 cell but now times seen = 3
and so on and so forth until max recursion.

Related

Minimum number of steps to convert the matrix by swapping

I stumbled upon the below question and was unable to solve it, can someone tell whats the approach here
There's no way to do this except by brute force, recursively. For each tile that's not in the right position, there are at most 4 possible swaps to make. You make a swap, then add this new position to the list of ones you haven't tried, making sure not to go back to any position you've seen before. Track the depth of the recursion, and when you get a final position, the depth is the answer.
incoming = (7,3,2,4,1,5,6,8,9)
answer = (1,2,3,4,5,6,7,8,9)
primes = (2,3,5,7,11,13,17)
def solve(base, depth):
seen = set()
untried = [(base,0)]
while untried:
array,depth = untried.pop(0)
print(depth, array)
if array == answer:
print( "ANSWER!", depth )
return depth
if array in seen:
print("seen")
continue
seen.add( array )
for n in range(9):
if array[n] == n+1:
continue
for dx in (-1, -3, 1, 3):
if 0 <= n+dx < 9 and array[n]+array[n+dx] in primes:
# attempt a swap.
a = list(array)
a[n],a[n+dx] = a[n+dx],a[n]
untried.append((tuple(a),depth+1))
print( "fail" )
return -1
solve( incoming, 0 )

Julia NLopt force stops before the first iteration

I'm using NLopt for a constrained maximization problem. Regardless of the algorithm or start values, the optimization program is force stopped even before the first iteration (or so I assume because it gives me the initial value). I've attached my code here. I'm trying to find probabilities attached to a grid such that a function is maximized under some constraints. Any help is appreciated.
uk = x -> x^0.5
function objective(u,p,grd)
-p'*u.(grd)
end
function c3(grd,p)
c =[]
d =[]
for i=1:length(grd)
push!(c,quadgk(x -> (i-x)*(x <= i ? 1 : 0),0,1)[1])
push!(d,sum(p[1:i]'*(grd[1:i] .- grd[i])))
end
return append!(d-c,-p)
end
function c4(grd,p)
return (grd .* p)-quadgk(x,0,1)
end
grd = n -> collect(0:1/n:1)
opt = Opt(:LD_SLSQP,11)
inequality_constraint!(opt, p -> c3(grd(10),p))
inequality_constraint!(opt, p -> -p)
equality_constraint!(opt, p -> sum(p)-1)
equality_constraint!(opt, p -> c4(grd(10),p))
opt.min_objective = p -> objective(-uk, p, grd(10))
k = push!(ones(11)*(1/11))
(minf,minx,ret) = optimize(opt, k)
I'm not a julia developer, but I only know this, if you need exit before complete the loop for is not your best choice, you need do a while with a sentinel variable.
here you have an article that explain you how while with sentinels works
and here you have a julia example changing your for to a while with a sentinel that exit after the third loop
i = 1
third = 0
while i < length(grd) && third != 1
# of course you need change this, it is only an example that will exit in the 3 loop
if i == 3
third = 1
end
push!(c,quadgk(x -> (i-x)*(x <= i ? 1 : 0),0,1)[1])
push!(d,sum(p[1:i]'*(grd[1:i] .- grd[i])))
i += 1
end

Getting the exact data index from a click on pyqt5graph image (not just pixel value)

I am new to PyqtGraph ( Infact this is my first time)
I have a Qt designer file which I import in my python code. I 6 windows in which I plot a 42x22 (different sizes) as an inmage, these have been promoted the graphicview.
I have a data set which is 6x42x22 and so I use a for loop to plot the 6 images
for n in range(imageStackSize):
self.glayout = pg.GraphicsLayout()
self.vb = self.glayout.addViewBox()
self.vb.setAspectLocked(lock=True, ratio=self.aspect_ratio)
img_temp = image[n, :, :]
and...
``
img = pg.ImageItem(img_temp, lut=self.jet_lut)
if n == 0:
self.ui.Channel1_img.setCentralItem(self.glayout)
self.vb.addItem(img)
elif n == 1:
self.ui.Channel2_img.setCentralItem(self.glayout)
self.vb.addItem(img)
elif n == 2:
self.ui.Channel3_img.setCentralItem(self.glayout)
self.vb.addItem(img)
elif n == 3:
self.ui.Channel4_img.setCentralItem(self.glayout)
self.vb.addItem(img)
elif n == 4:
self.ui.Channel5_img.setCentralItem(self.glayout)
self.vb.addItem(img)
elif n == 5:
self.ui.Channel6_img.setCentralItem(self.glayout)
self.vb.addItem(img)
After this I am trying to click on one of the image (ideally I would like to make it such that I can click any of the six images) to get the (6,x,y) coordinated the first dimension does not matter. In order to achieve this I did
self.ui.Channel1_img.scene().sigMouseClicked.connect(self.onClick)
#self.ui.Channel2_img.scene().sigMouseClicked.connect(self.onClick)
#self.ui.Channel3_img.scene().sigMouseClicked.connect(self.onClick)
#self.ui.Channel4_img.scene().sigMouseClicked.connect(self.onClick)
#self.ui.Channel5_img.scene().sigMouseClicked.connect(self.onClick)
#self.ui.Channel6_img.scene().sigMouseClicked.connect(self.onClick)
#self.ui.PMTVoltage_plt.scene().sigMouseClicked.connect(self.onClick)
def onClick(self, event):
print("clicked")
and then I tried
items = self.ui.Channel1_img.imageItem.mapFromViewToItem(event.pos())
and
items = self.ui.Channel1_img.imageItem.mapFromSceneToView(event.pos())
but the prog just crashes. I read somewhere that the coordinates are in the viewbox, but I cant seem to find the viewbox or vb in the self.ui.Channel1_img
I went through the entire ui variable in debug to look for vb or image Item and could not find it.
infact the only thing I found was,
items = {dict} {<pyqtgraph.graphicsItems.ViewBox.ViewBox.ViewBox
object at 0x000001CF73888CA8>: [(0, 0)]}
<pyqtgraph.graphicsItems.ViewBox.ViewBox.ViewBox object at
0x000001CF73888CA8> (1990508186792) = {list} <class 'list'>: [(0, 0)]
0 = {tuple} <class 'tuple'>: (0, 0)
0 = {int} 0
1 = {int} 0
__len__ = {int} 2
__len__ = {int} 1
__len__ = {int} 1
what am I missing? Any help is appreciated
Ok I figured it out, here is my solution for some who may have same question
I plot the data using it as imageItem
vb = pg.ViewBox()
self.ui.PMTVoltage_plt.useOpenGL()
self.ui.PMTVoltage_plt.setCentralItem(vb)
self.img = pg.ImageItem(pmtImage)
vb.addItem(self.img)
and then in other function I recover the vb using getViewBox() and then use mapFromViewtoItem()
vb = self.ui.PMTVoltage_plt.getViewBox()
items = vb.mapSceneToView(event.scenePos())
pixels = vb.mapFromViewToItem(self.img, items)
print(items)
Hope this helps

Simple recursive series in matlab

I'm trying to get the sum of the first 120 terms of a series:
a(n) = (10+a(n-1))(1.005)^n
I've tried two approaches, but I don't know which mistakes I'm making.
Approach #1:
nval = 1
mval = zeros(120,1)
for nval=1:120
if nval <= 120 %counting up from 1 to 120
if nval == 1 %modifying first term to avoid 0 index
mval(1) = (10)*(1.005)
nval = nval +1;
else
mval(nval) = (10+mval(nval-1))*(1.005)^nval; %Assigning
nval = nval +1;
end
end
end
which results in a column vector with 10.05 at the top and zeroes for the rest. If if omit the opening definition of mval as zeroes, I get the same result as
Approach #2:
a(1)=10.05; %defining first term to avoid 0 index
for n=2:120, a(n)= (10+a(n-1))*(1.005)^n; end
which results in something far too large.
(The correct value for a(120) is ~1646.99)
Edit: my mistake and apologies - my series was wrong; the (1.005)^n is NOT to the nth power, but merely 1.005. Using this, both methods work.
Thanks to one and all for answers and suggestions

if a<x<b in matlab

I need any help for Matlab's thinking method.Ithink I can explaine my problem with a simple example better. Let's say that I have a characteristic function x=y+x0, x0's are may starting values.Then I want to define my function in a grid.Then I define a finer grid and I want to ask him if he knows where an arbitrary (x*,y*) is.To determine it mathematically I should ask where the corresponding starting point (x0*) is. If this startig point stay between x(i,1)
clear
%%%%%%%%%%&First grid%%%%%%%%%%%%%%%%%%%%
x0=linspace(0,10,6);
y=linspace(0,5,6);
for i=1:length(x0)
for j=1:length(y)
x(i,j)=y(j)+x0(i);
%%%%%%%%%%%%%%%%%%%Second grid%%%%%%%%%%%%%%%%%%
x0fine=linspace(0,10,10);
yfine=linspace(0,5,10);
for p=1:length(x0fine)
for r=1:length(yfine)
xfine(p,r)=yfine(r)+x0fine(p);
if (x(i,1)<xfine(p,1)')&(x0fine(p,1)'<x(i+1,1))%%%%I probabliy have my first mistake %here
% if y(j)<yfine(r)<y(j+1)
% xint(i,j)=(x(i,j)+x(i,j+1)+x(i+1,j)+x(i+1,j+1))./4;
% else
% xint(i,j)= x(i,j);
%end
end
end
end
end
While a < b < c is legal MATLAB syntax, I doubt that it does what you think it does. It does not check that a < b and b < c. What it does is, it checks whether a < b, returning a logical value (maybe an array of logicals) and then, interpreting this logical as 0 or 1, compares it against c:
>> 2 < 0 < 2
ans =
1
>> 2 < 0 < 1
ans =
1
>> 0 < 0 < 1
ans =
1
First in matlab you should avoid as much as possible to do loops.
For instance you can compute x and xfine, with the following code:
x0=linspace(0,10,6);
y=linspace(0,5,6);
x=bsxfun(#plus,x0',y);
x0fine=linspace(0,10,10);
yfine=linspace(0,5,10);
xfine=bsxfun(#plus,x0fine',yfine);
Then given (X*,y*) your want to fine x0*, in your simple example, you can just do: x0*=x*-y*, I think.

Resources