[Edu-sig] Sample Data Structure
Gregor Lingl
glingl at aon.at
Tue Jun 27 19:08:48 CEST 2006
kirby urner schrieb:
>> I doubt if it is a good choice to use a dictionary here, as this is not
>> an ordered data
>> structure and interchanging the layers of the cube will certainly make
>> the cube
>> imperfect.
>
> Yes, I think you're right. I was trying to advertise dictionary
> syntax, but not appropriately in this case. My earlier draft was
> nested tuples, and I could have stuck with that, but thought it too
> boring.
>
> A more complete module would also have audit code that actually summed
> all the rows, columns and diagonals, and spit out 315 every time.
>
> I've written most of this auditing code, but decided the bare data
> would be better.
>
I did a similar thing, deciding to use a flat list. If one used the flat
list *and* the
(given) nested one(s) one could make the code even more compact.
My solution goes like this:
from operator import __and__
magic5 = [
[[25, 16, 80, 104, 90],
[115, 98, 4, 1, 97],
[42, 111, 85, 2, 75],
[66, 72, 27, 102, 48],
[67, 18, 119, 106, 5]],
[[91, 77, 71, 6, 70],
[52, 64, 117, 69, 13],
[30, 118, 21, 123, 23],
[26, 39, 92, 44, 114],
[116, 17, 14, 73, 95]],
[[47, 61, 45, 76, 86],
[107, 43, 38, 33, 94],
[89, 68, 63, 58, 37],
[32, 93, 88, 83, 19],
[40, 50, 81, 65, 79]],
[[31, 53, 112, 109, 10],
[12, 82, 34, 87, 100],
[103, 3, 105, 8, 96],
[113, 57, 9, 62, 74],
[56, 120, 55, 49, 35]],
[[121, 108, 7, 20, 59],
[29, 28, 122, 125, 11],
[51, 15, 41, 124, 84],
[78, 54, 99, 24, 60],
[36, 110, 46, 22, 101]]
]
def flatten(lol):
flat = []
for l in lol:
flat.extend(l)
return flat
## This approach - using slices - operates best with a flat list
def msq(s):
return reduce(__and__, (
[sum(s[i:i+5])==315 for i in range(0,25,5)] +
[sum(s[i:25:5])==315 for i in range(5)] +
[sum(s[0:25:6])==315, sum(s[4:21:4])==315]))
def magic(cube):
sq=flatten([flatten(sq) for sq in cube])
return reduce(__and__, (
[msq(sq[i:i+25]) for i in range(0,125,25)] +
[msq(sq[i:125:5]) for i in range(5)] +
[msq(flatten([sq[i+j:i+j+5] for i in
range(0,125,25)])) for j in range(0,21,5)] +
[sum(s)==315 for s in
[sq[0:125:31],sq[20:105:21],sq[4:121:29],sq[24:101:19]]]))
print magic(magic5)
# I wonder how it will look like with a 3-dimensional list
Regards,
Gregor
More information about the Edu-sig
mailing list