bajotupie - 1 year ago 52

Python Question

So on a list I need to check if 'z' is in the same row as the case selected and return True, but if something is on the way for example 'x' it returns False. I made a code but the problem it has is that if there is two 'z's and the one on the left is blocked by an 'x' but the other one is not, it returns False but it should be True. It works fine for the other cases. Hope you get me, I'm pretty bad explaining these things.

`def row(lst,i,j):`

c = 0

if 'z' not in lst[i]:

c += 1

else:

for n in range(0,len(lst[i])):

if lst[i][n] == 'z' and n > j:

for m in range(j,n):

if lst[i][m] == 'x':

c += 1

else:

c = 0

break

if lst[i][n] == 'z' and j > n:

for m in range(n,j):

if lst[i][m] == 'x':

c += 1

else:

c = 0

break

if c > 0:

return False

elif c == 0:

return True

I don't really know what exactly does 'break' here but it works

The list I use is:

`lst = [['_','_','_','_','_'],['z','x','_','_','z'],['_','_','x','_','_']]`

and the case I'm checking is lst[1][2].

`['_','x','_','_','z']`

returns True, there is a 'z' in the row.

`['_','x','_','x','z']`

returns False, z is being blocked

`['z','x','_','x','z']`

returns False

`['z','x','_','_','z']`

PROBLEM: should return True

Answer Source

There are two halves of the row to check. The one before (i, j) and the one after (i, j).

The problem is that you're breaking before you reach the second half.
Plus, I'm not sure what you're doing with *c*.

Anyway, one solution could be this:

```
def check_row(lst, i, j):
if 'z' not in lst[i]:
return False
for n in range(j, 0, -1):
if lst[i][n] == 'z':
return True
elif lst[i][n] == 'x':
break
for n in range(j + 1, len(lst[i])):
if lst[i][n] == 'z':
return True
elif lst[i][n] == 'x':
break
return False
```

The idea is to look *out* from the target value.
First, we loop from the target to the front of the row, and then we loop from the target to the end of the row. At any point, if it encounters 'z', we return True immediately. If it encounters 'x', we break the search in that direction. We have been blocked.

If we reach the end, it means we haven't found 'z', so we return False.

This could probably be made much shorter but this basic version should work.