How can I shorten this python code analyzing a 3d grid?
Python 3, 108 107 bytes
Since the cube only contains the strings "X"
and "Z"
, there are only two valid cube patterns. The one that starts with XZXZX...
and the one that starts with ZXZXZ...
.
My solutions generates these 2 cubes and checks if the inputted cube is one of them.
def golf(l):L=len(l);r=range(L);return l in[[[list("XZ"*L)[(i+j+k)%2:][:L]for j in r]for k in r]for i in r]
i
iterates over the possible cubes. Since the dimension is at least 2, we can reuse r
instead of writing for i in(0,1)
.
Python 3, 60 bytes
golf=g=lambda l:all(g(a)*g(b)*(a!=b)for a,b in zip(l,l[1:]))
The function recursively decides whether an N-dimensional array is alternating by checking if:
- Any two adjacent elements are unequal
- Each element is alternating
This successfully bottoms out for the strings 'X'
and 'Z'
because their length is 1
, so the all
is taken of an empty list.
Python 3 with NumPy, 125 bytes
import numpy
def golf(a):a=numpy.array(a);return(a[:-1]!=a[1:]).all()&(a[:,:-1]!=a[:,1:]).all()&(a[:,:,:-1]!=a[:,:,1:]).all()
Python 3, 146 128 bytes
e=lambda x,y:x!=y
z=lambda f:lambda*l:all(map(f,*l))
u=lambda f,g:lambda a:z(f)(a,a[1:])&z(g)(a)
golf=u(z(z(e)),u(z(e),u(e,id)))