473,791 Members | 3,111 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

searching a list of lists as a two-dimensional array?

Basically I'm programming a board game and I have to use a list of
lists to represent the board (a list of 8 lists with 8 elements each).
I have to search the adjacent cells for existing pieces and I was
wondering how I would go about doing this efficiently. Thanks

Feb 12 '07 #1
16 3661
agent-s wrote:
Basically I'm programming a board game and I have to use a list of
lists to represent the board (a list of 8 lists with 8 elements each).
I have to search the adjacent cells for existing pieces and I was
wondering how I would go about doing this efficiently. Thanks
This isn't very clear. What do you mean by "I have to search the
adjacent cells for existing pieces"?

If piece is 1 and empty is 0 and piece is at ary[row][col]:

import operator
srch = [(i,j) for i in [-1,0,1] for j in [-1,0,1] if (i,j) != (0,0)]
is_adj = reduce(operator .or_, [ary[row+i][col+j] for (i,j) in srch]])
James
Feb 12 '07 #2
James Stroud <js*****@mbi.uc la.eduon Sun, 11 Feb 2007 16:53:16 -0800
didst step forth and proclaim thus:
agent-s wrote:
Basically I'm programming a board game and I have to use a list of
lists to represent the board (a list of 8 lists with 8 elements each).
I have to search the adjacent cells for existing pieces and I was
wondering how I would go about doing this efficiently. Thanks

This isn't very clear. What do you mean by "I have to search the
adjacent cells for existing pieces"?

If piece is 1 and empty is 0 and piece is at ary[row][col]:

import operator
srch = [(i,j) for i in [-1,0,1] for j in [-1,0,1] if (i,j) != (0,0)]
is_adj = reduce(operator .or_, [ary[row+i][col+j] for (i,j) in srch]])
Wow, maybe it's just me (I'm a pretty bad programmer) but this is
where list comprehensions begin to look unreadable to me. Here's a
C-like way to do it, (warning, untested in python):

for i in range(8):
for j in range(8):
for offset_i in range(-1,2):
for offset_j in range(-1, 2):
row = i + offset_i
col = j + offset_j
if (row < 0 or row 7) or (col < 0 or col 8) \
or ((row,col) == (i,j)):
continue
# else do something with board[row][col]

I realize this is gross and un-Pythonic and does the same thing the
above code does, but it's probably the way I'd choose to do it :).
Then again, I've been negatively influenced by doing a game of life in
C a few months back.

--
Sam Peterson
skpeterson At nospam ucdavis.edu
"if programmers were paid to remove code instead of adding it,
software would be much better" -- unknown
Feb 12 '07 #3
En Mon, 12 Feb 2007 02:24:54 -0300, Samuel Karl Peterson
<sk********@nos pam.please.ucda vis.eduescribió :
James Stroud <js*****@mbi.uc la.eduon Sun, 11 Feb 2007 16:53:16 -0800
didst step forth and proclaim thus:
>agent-s wrote:
Basically I'm programming a board game and I have to use a list of
lists to represent the board (a list of 8 lists with 8 elements each).
I have to search the adjacent cells for existing pieces and I was
wondering how I would go about doing this efficiently. Thanks
Wow, maybe it's just me (I'm a pretty bad programmer) but this is
where list comprehensions begin to look unreadable to me. Here's a
C-like way to do it, (warning, untested in python):
Just for fun, and to add one more way. This is a generator for adjacent
indexes, that can be used to search for occupied cells, for locating a
suitable next move, or whatever:

pydef adj(i, j):
.... for ni in (i-1, i, i+1):
.... if ni not in range(8): continue
.... for nj in (j-1, j, j+1):
.... if nj not in range(8): continue
.... if ni!=i or nj!=j:
.... yield ni,nj
....
py>
pyprint list(adj(4,3))
[(3, 2), (3, 3), (3, 4), (4, 2), (4, 4), (5, 2), (5, 3), (5, 4
pyprint list(adj(7,3))
[(6, 2), (6, 3), (6, 4), (7, 2), (7, 4)]
pyprint list(adj(4,7))
[(3, 6), (3, 7), (4, 6), (5, 6), (5, 7)]
pyprint list(adj(0,7))
[(0, 6), (1, 6), (1, 7)]

--
Gabriel Genellina

Feb 12 '07 #4
En Mon, 12 Feb 2007 02:24:54 -0300, Samuel Karl Peterson
<sk********@nos pam.please.ucda vis.eduescribió :
James Stroud <js*****@mbi.uc la.eduon Sun, 11 Feb 2007 16:53:16 -0800
didst step forth and proclaim thus:
>agent-s wrote:
Basically I'm programming a board game and I have to use a list of
lists to represent the board (a list of 8 lists with 8 elements each).
I have to search the adjacent cells for existing pieces and I was
wondering how I would go about doing this efficiently. Thanks
Wow, maybe it's just me (I'm a pretty bad programmer) but this is
where list comprehensions begin to look unreadable to me. Here's a
C-like way to do it, (warning, untested in python):
Just for fun, and to add one more way. This is a generator for adjacent
indexes, that can be used to search for occupied cells, for locating a
suitable next move, or whatever:

pydef adj(i, j):
.... for ni in (i-1, i, i+1):
.... if ni not in range(8): continue
.... for nj in (j-1, j, j+1):
.... if nj not in range(8): continue
.... if ni!=i or nj!=j:
.... yield ni,nj
....
py>
pyprint list(adj(4,3))
[(3, 2), (3, 3), (3, 4), (4, 2), (4, 4), (5, 2), (5, 3), (5, 4
pyprint list(adj(7,3))
[(6, 2), (6, 3), (6, 4), (7, 2), (7, 4)]
pyprint list(adj(4,7))
[(3, 6), (3, 7), (4, 6), (5, 6), (5, 7)]
pyprint list(adj(0,7))
[(0, 6), (1, 6), (1, 7)]

--
Gabriel Genellina

Feb 12 '07 #5
"agent-s" <sh*******@gmai l.comwrites:
Basically I'm programming a board game and I have to use a list of
lists to represent the board (a list of 8 lists with 8 elements each).
I have to search the adjacent cells for existing pieces and I was
wondering how I would go about doing this efficiently. Thanks
You're getting a bunch of Pythonic suggestions which are easy to
understand though not so efficient. If you're after efficiency you
might look at a book like Welsh and Baczynskyj "Computer Chess II" for
some techniques (warning, this is a rather old book though) and
program in a closer-to-the-metal language. One common approach these
days is "bit boards". Basically you represent the board state as a
bunch of 64-bit words, one bit per square. So for checking occupancy,
you'd have a word having the bits set for occupied squares. If you
only want to check adjacent squares (king moves), you could have a
bunch of bit masks (one for each square) with bits set only for the
adjacent squares (similarly for bishop moves, rook moves, etc.) Then
to check adjacency you'd mask off the appropriate bits for that
square, then AND it against the occupancy word. Normally you'd have
separate occupancy words for your own pieces and your opponent's.
Feb 12 '07 #6
Paul Rubin wrote:
"agent-s" <sh*******@gmai l.comwrites:
>>Basically I'm programming a board game and I have to use a list of
lists to represent the board (a list of 8 lists with 8 elements each).
I have to search the adjacent cells for existing pieces and I was
wondering how I would go about doing this efficiently. Thanks


You're getting a bunch of Pythonic suggestions which are easy to
understand though not so efficient. If you're after efficiency you
might look at a book like Welsh and Baczynskyj "Computer Chess II" for
some techniques (warning, this is a rather old book though) and
program in a closer-to-the-metal language. One common approach these
days is "bit boards". Basically you represent the board state as a
bunch of 64-bit words, one bit per square. So for checking occupancy,
you'd have a word having the bits set for occupied squares. If you
only want to check adjacent squares (king moves), you could have a
bunch of bit masks (one for each square) with bits set only for the
adjacent squares (similarly for bishop moves, rook moves, etc.) Then
to check adjacency you'd mask off the appropriate bits for that
square, then AND it against the occupancy word. Normally you'd have
separate occupancy words for your own pieces and your opponent's.
In defense of the less efficient suggestions, he did say he had to use a
list of lists. But what you describe is pretty cool.

James
Feb 12 '07 #7
James Stroud:
import operator
srch = [(i,j) for i in [-1,0,1] for j in [-1,0,1] if (i,j) != (0,0)]
is_adj = reduce(operator .or_, [ary[row+i][col+j] for (i,j) in srch]])
Or maybe (untested), Python V.2.5:

srch = [(i,j) for i in [-1,0,1] for j in [-1,0,1] if (i,j) != (0,0)]
is_adj = any(ary[row+i][col+j] for (i,j) in srch)

Or:

is_adj = any(ary[row+i][col+j] for i in [-1,0,1] for j in [-1,0,1] if
(i,j) != (0,0))

Bye,
bearophile

Feb 12 '07 #8
On Feb 12, 4:24 pm, Samuel Karl Peterson
<skpeter...@nos pam.please.ucda vis.eduwrote:
C-like way to do it, (warning, untested in python):

for i in range(8):
for j in range(8):
for offset_i in range(-1,2):
for offset_j in range(-1, 2):
row = i + offset_i
col = j + offset_j
if (row < 0 or row 7) or (col < 0 or col 8) \
or ((row,col) == (i,j)):
continue
# else do something with board[row][col]

I realize this is gross and un-Pythonic and does the same thing
It's also just a little bit inefficient. Never mind the algorithm,
we'll talk about that later. Let's just improve the code a little:

side_range = range(8)
delta_range = range(-1, 2)
for i in side_range:
for offset_i in delta_range:
row = i + offset_i
if not (0 <= row <= 7): continue
for j in side_range:
for offset_j in delta_range:
if not offset_i and not offset_j: continue
col = j + offset_j
if not(0 <= col <= 7): continue
# *now* it's safe to do something
# with (row, col)

Such hoisting of code out of inner loops is done for you by a C
compiler -- Python assumes you know what you are doing :-)

Now for the algorithm: all of that testing to see if you are about to
sail off the end of the world is a bit ugly and slow. You can use bit-
bashing, as Paul suggested, even though it's on Steven D'Aprano's list
of 6 deadly sins :-)

Another approach that has been used is to have a 9 x 9 storage area;
the squares off the edge contain a value that is neither "empty" nor
any value that represents a piece. So with careful coding, they
automatically fail tests like "can I capture the piece on this
square" [no, it's not a piece] and "can I move here" [no, it's not
empty]. If the game is chess, you need 10 x 10 to cater for those
pesky knights.

Cheers,
John

Feb 12 '07 #9
On Sun, 11 Feb 2007 23:20:11 -0800, John Machin wrote:
Now for the algorithm: all of that testing to see if you are about to
sail off the end of the world is a bit ugly and slow. You can use bit-
bashing, as Paul suggested, even though it's on Steven D'Aprano's list
of 6 deadly sins :-)
Heh. Being a smart-alec is number 7 :-P

Seriously, this is Python. Are you *sure* bit-bashing is going to be
faster than the alternative? If this was C, or assembly, you'd almost
certainly be right. But Python is heavily object-oriented, and bit
manipulations are just methods, with all the overhead that entails.
>>import timeit
timeit.Timer( "3 | 2", "").repeat( )
[0.3367800712585 4492, 0.3344750404357 9102, 0.3333101272583 0078]
>>timeit.Timer( "3 < 2", "").repeat( )
[0.3032889366149 9023, 0.2907011508941 6504, 0.2883939743041 9922]

The problem with bit-bashing, masking etc. is that except for the most
simple cases it is quite obfuscated. If you aren't going to gain a serious
performance boost, why bother?


--
Steven D'Aprano

Feb 12 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
8255
by: Kakarot | last post by:
I'm gona be very honest here, I suck at programming, *especially* at C++. It's funny because I actually like the idea of programming ... normally what I like I'm atleast decent at. But C++ is a different story. Linked lists have been giving me a headache. I can barely manage to create a single/doubly linked list, it's just that when it gets to merge sorting or searching (by reading shit data from text files), I lose track.
0
1122
by: Joshua Spoerri | last post by:
Which version is targetted for optimization of OR searching on two keys, that is, "select * from sometable where f1 = 123 or f2 = 123", as described in http://www.mysql.com/doc/en/Searching_on_two_keys.html ? Thanks -- MySQL General Mailing List
8
5800
by: simpleman | last post by:
Hi, I have an assignment that requires me to subtract two very large unsigned integers using linked list.AFAIK I have to manipulate data as character. But I dont know how to get input into the linked list since the input will all be in one line. eg. 1234567890. Also I have to use one integer per node. Any help/suggestion will be greatly appreciated. Thanks in advance
2
1687
by: Tim Pollard | last post by:
Hi I'm hoping someone can help me with an access problem I just can't get my head around. I normally use access as a back end for asp pages, just to hold data in tables, so queries within access are a mystery to me, but I can't think of any other way of dealing with the problem. I have six tables in my db: tblCompanies (list of companies, primary key CompanyID) tblOffices (list of office buildings including what company owns/uses
1
12847
by: Booser | last post by:
// Merge sort using circular linked list // By Jason Hall <booser108@yahoo.com> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> //#define debug
11
2831
by: Neo | last post by:
Hi Frns, Could U plz. suggest me how can i reverse a link list (without recursion)??? here is my code (incomplete): #include<stdio.h>
4
3600
by: MJ | last post by:
Hi I have written a prog for reversing a linked list I have used globle pointer Can any one tell me how I can modify this prog so that I dont have to use extra pointer Head1. When I reverse a LL using the recursive call how to change the last node pointer to head and head->next to null without using the extra global pointer Mayur
0
1437
by: daveleominster | last post by:
I am trying to read in a XML file into to vb.net say I have a text box and I am searching for a command "Aname" I enter the text and push the button, I want my syntax info and summary info to appear on the next form in a two separate list box. So I am thinking a loop and if statements are need. What do you suggestion for the vb code Next if the there is no commandname that match then it search for a keyword and then lists the commands...
20
2429
by: Seongsu Lee | last post by:
Hi, I have a dictionary with million keys. Each value in the dictionary has a list with up to thousand integers. Follow is a simple example with 5 keys. dict = {1: , 2: , 900000: , 900001: ,
46
3427
by: junky_fellow | last post by:
Hi, Is there any efficient way of finding the intesection point of two singly linked lists ? I mean to say that, there are two singly linked lists and they meet at some point. I want to find out the addres of the node where the two linked intersect. thanks for any help...
0
9517
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10428
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10207
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10156
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9997
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6776
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5435
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4110
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2916
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.