I am trying to get a index of items to the left, right, bottom, and top of a binary integer in a 4x4 grid. With what I am doing now doesn't seem to be getting the correct index of a value.
if self.data[index] == 1:
self.data[index] = 0
if self.data.index(self.data[index]) - 1 >= 0:
print("Left toggled")
if self.data[index - 1] == 1:
self.data[index - 1] = 0
else:
self.data[index - 1] = 1
As of now I am trying with the bit array of 010011100100
which is returning a -1 if index = 5
in the above code example when it should be returning 4 as 5-1=4.
I assume my if statement if self.data.index(self.data[index]) - 1 >= 0:
is wrong, but I am unsure of the syntax of what I am trying to accompish.
Lets step through your code and see what happens...
#We'll fake these in so the code makes sence...
#self.data must be an array as you can't reassign as you are doing later
self.data = list("010011100100")
index = 5
if self.data[index] == 1: # Triggered, as self.data[:5] is "010011"
self.data[index] = 0 # AHA self.data is now changed to "010010..."!!!
if self.data.index(self.data[index]) - 1 >= 0:
#Trimmed
In the second last line you are getting self.data[index]
which is now 0
as we changed it the line before.
But also, remember that Array.index()
returns the first instance of that item in the array. So self.data.index(0)
returns the first instance of 0
, which is the first or more precicely, zeroth element. Thus is self.data.index(0)
gives 0
and 0-1
is... -1
.
As for what your code should be, that is a tougher answer.
I think your conditional may just be:
width = 4 # For a 4x4 grid, defined much earlier.
height = 4 # For a 4x4 grid, defined much earlier.
...
if index%width == 0:
print "we are on the left edge"
if index%width == width - 1:
print "we are on the right edge"
if index%height == 0:
print "we are on the top edge"
if index%height == height - 1:
print "we are on the bottom edge"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.