how to get individual numbers of a box - python

I'm struggling to get each of the four numbers of a python array contained within a 2x2 into their separate arrays much like a Sudoku grid. Order doesn't matter. I would have tried writing a code or something but my mind has gone blank.
example grid
[
[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]
]
I want to be able to get it in the form
[
[ 1, 2, 5, 6],
[ 3, 4, 7, 8],
[ 9, 10, 13, 14],
[11, 12, 15, 16]
]

Here is a pure Python solution. If you are after something more readable consider using NumPy (see below).
>>> from itertools import count, chain
>>>
# create 2x2 blocks of 2x2
>>> c = count(1)
>>> L4D = [[[[next(c) for i in range(2)] for j in range(2)] for k in range(2)] for l in range(2)]
>>> L4D
[[[[1, 2], [3, 4]], [[5, 6], [7, 8]]], [[[9, 10], [11, 12]], [[13, 14], [15, 16]]]]
# swap middle dimensions
>>> L4D = [zip(*i) for i in L4D]
# next line is not necessary, only here so we can see what's going on
>>> L4D = [list(i) for i in L4D]
>>> L4D
[[([1, 2], [5, 6]), ([3, 4], [7, 8])], [([9, 10], [13, 14]), ([11, 12], [15, 16])]]
# join first two and last two dimensions
>>> result = [list(chain.from_iterable(j)) for j in chain.from_iterable(L4D)]
>>> result
[[1, 2, 5, 6], [3, 4, 7, 8], [9, 10, 13, 14], [11, 12, 15, 16]]
If using NumPy is an option this can be simplified. Here are three different possibilities. The first is a direct translation of the pure Python solution:
>>> import numpy as np
>>>
>>> np.arange(1, 17).reshape(2, 2, 2, 2).swapaxes(1, 2).reshape(4, 4)
array([[ 1, 2, 5, 6],
[ 3, 4, 7, 8],
[ 9, 10, 13, 14],
[11, 12, 15, 16]])
>>> np.block(list(map(list, np.arange(1, 17).reshape(2, 2, 2, 2))))
array([[ 1, 2, 5, 6],
[ 3, 4, 7, 8],
[ 9, 10, 13, 14],
[11, 12, 15, 16]])
>>> a = np.arange(4).reshape(2, 2)
>>> b = np.ones((2, 2), dtype = int)
>>> 4 * np.kron(a, b) + np.kron(b, a) + 1
array([[ 1, 2, 5, 6],
[ 3, 4, 7, 8],
[ 9, 10, 13, 14],
[11, 12, 15, 16]])

I finally found a solution to my question with a little modification to this answer
cells = [[] * 4 for x in range(4)]
for row_index, row in enumerate(grid):
for col_index, col in enumerate(row):
i = col_index//2 + 2*(row_index//2)
cells[i].append(col)

Related

Create multidimensional torch tensor time series

I want to create a torch tensor sequence out of a multi-dimensional numpy array. I've achieved it with 1-d arrays, but can't find the proper way with more dimensions...
This is a 1-d vector example:
import numpy as np
import torch
n = np.arange(10)
t = torch.tensor([n[i: i + 3] for i in range(7)])
Being the output:
tensor([[0, 1, 2],
[1, 2, 3],
[2, 3, 4],
[3, 4, 5],
[4, 5, 6],
[5, 6, 7],
[6, 7, 8]])
Let's say that instead of a 1-d vector I have a 2-d one.
import numpy as np
import torch
n = np.array([np.arange(10), np.arange(10, 20)])
t = torch.tensor([n[..., i: i + 3] for i in range(7)]).view(2, -1, 3)
The output is:
tensor([[[ 0, 1, 2],
[10, 11, 12],
[ 1, 2, 3],
[11, 12, 13],
[ 2, 3, 4],
[12, 13, 14],
[ 3, 4, 5]],
[[13, 14, 15],
[ 4, 5, 6],
[14, 15, 16],
[ 5, 6, 7],
[15, 16, 17],
[ 6, 7, 8],
[16, 17, 18]]])
And what I’m looking for is:
tensor([[[ 0, 1, 2],
[ 1, 2, 3],
[ 2, 3, 4],
[ 3, 4, 5],
[ 4, 5, 6],
[ 5, 6, 7],
[ 6, 7, 8]],
[[10, 11, 12],
[11, 12, 13],
[12, 13, 14],
[13, 14, 15],
[14, 15, 16],
[15, 16, 17],
[16, 17, 18]]])
As you can see the rows are alternated... Is there any way of achieving it?
P.D: In case there is a more elegant solution to solve the problem, I will be very grateful too! I've tried with methods as torch.repeat_interleave but couldn't achieve anything...
Thanks a lot!
It is not very clear what formula you want to implement, but looks like it should be t[i, j, k] = i*10 + j + k. This formula is nothing but the outer sum of the three index ranges. The most straightforward way to obtain it is
t = torch.tensor(np.add.outer(np.arange(2)*10, np.add.outer(np.arange(7), np.arange(3))))
Which gives
tensor([[[ 0, 1, 2],
[ 1, 2, 3],
[ 2, 3, 4],
[ 3, 4, 5],
[ 4, 5, 6],
[ 5, 6, 7],
[ 6, 7, 8]],
[[10, 11, 12],
[11, 12, 13],
[12, 13, 14],
[13, 14, 15],
[14, 15, 16],
[15, 16, 17],
[16, 17, 18]]], dtype=torch.int32)
You can achieve this by concatenating the sub-tensors along the appropriate axis:
n = np.array([np.arange(10), np.arange(10, 20)])
t = torch.tensor([n[..., i: i + 3] for i in range(7)])
t = torch.cat([_ for _ in t.unsqueeze(-2)], dim=1)

Replacing a vertical sublist in a list of lists

This question is an extension to this question.
I'm representing a two-dimensional array using list of lists, L, say:
[ [1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4] ]
For a given sub-list, say [9, 99], I want to replace a specific sub-list in the "2-D" list by this sublist using something intuitive like:
L[1][0:2] = sublist
# which updates `L` to:
[ [1, 2, 3, 4],
[1, 9, 99, 4],
[1, 2, 3, 4],
[1, 2, 3, 4] ] # not in this format, but written like this for clarity
This works for horizontal replacements, but not for vertical replacements since, as we can't slice to separate lists like this: L[0:2][0]. If I had to use this slicing system, I could transpose L (Transpose list of lists), then use this slicing method, then transpose it back. But that's not efficient, even for the sake of simplicity.
What would be an efficient way to replicate L[0:2][0] and get this output?
[ [1, 2, 3, 4],
[1, 9, 3, 4],
[1, 99, 3, 4],
[1, 2, 3, 4] ]
Note: Assume len(sublist) <= len(L), for vertical replacements (which is the focus of this question).
Looping approach:
def replaceVert(al : list, repl:list, oIdx:int, iIdx:int):
for pos in range(len(repl)):
al[oIdx+pos][iIdx] = repl[pos]
a = [ [1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16] ]
print(a) # [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
replaceVert(a,['ä','ü'],2,2) # this is a one liner ;)
print(a) # [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 'ä', 12], [13, 14, 'ü', 16]]
Transpose/slice/transpose approach:
I overread the mentioning of "no transposing". This is using transpose, change, transpose method with slicing which is not wanted by the Q. It is a answer for the title of this question, so I decided to leave it in for future people search SO and stumble over this Q:
a = [ [1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16] ]
b = list(map(list,zip(*a))) # will make [ [1,5,9,13], ... ,[4,8,12,16]]
b[1][0:2]=['a','b'] # replaces what you want here (using a and b for clarity)
c = list(map(list,zip(*b))) # inverts b back to a's form
print(a)
print(b)
print(c)
Output:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] # a
[[1, 5, 9, 13], ['a', 'b', 10, 14], [3, 7, 11, 15], [4, 8, 12, 16]] # b replaced
[[1, 'a', 3, 4], [5, 'b', 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] # c
Timing 4x4 list, 2 replaces:
setuptxt = """
def replaceVert(al : list, repl:list, oIdx:int, iIdx:int):
for pos in range(len(repl)):
al[oIdx+pos][iIdx] = repl[pos]
a = [ [1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16] ]
"""
zipp = """b = list(map(list,zip(*a)))
b[1][0:2]=['a','b']
c = list(map(list,zip(*b)))
"""
import timeit
print(timeit.timeit("replaceVert(a,['ä','ü'],2,2)",setup = setuptxt))
print(timeit.timeit(stmt=zipp, setup=setuptxt))
Output:
looping: 12.450226907037592
zipping: 7.50479947070815
The method wit ZIPPing (transpose/slice/transpose) needs roughly 60% of the time for 4x4 lists.
Bigger list 1000x1000 and ~70 elements replaced:
setuptxt = """
def replaceVert(al : list, repl:list, oIdx:int, iIdx:int):
for pos in range(len(repl)):
al[oIdx+pos][iIdx] = repl[pos]
a = [ [kk for kk in range(1+pp,1000+pp)] for pp in range(1,1000)]
repl = [chr(mm) for mm in range(32,100)]
"""
import timeit
print(timeit.timeit("replaceVert(a,repl,20,5)",number=500, setup = setuptxt))
zipp = """b = list(map(list,zip(*a)))
b[20][5:5+len(repl)]=repl
c = list(map(list,zip(*b)))
"""
print(timeit.timeit(stmt=zipp, setup=setuptxt,number=500))
Output:
looping: 0.07702917579216137
zipping: 69.4807168493871
Looping wins. Thanks #Sphinx for his comment

Parameter update during function call

So, I am writing a code to shift the elements of a particular list within a list of lists towards right.
def right(state,index):
r_state=state
new_state = []
for j in range(1,len(r_state[index])):
new_state.append(r_state[index][j-1])
new_state.insert(0, r_state[index][-1])
r_state[index]=new_state
return r_state
#case1
for i in range(2):
print(right([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], i))
#case2
def printer(node):
for i in range(2):
print(right(node, i))
printer([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
case 1 gives me the output that I want(only one sublist corresponding to the index changed):
[[4, 1, 2, 3], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
[[1, 2, 3, 4], [8, 5, 6, 7], [9, 10, 11, 12], [13, 14, 15, 16]]
But case 2 ends up updating my list of lists
[[4, 1, 2, 3], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
[[4, 1, 2, 3], [8, 5, 6, 7], [9, 10, 11, 12], [13, 14, 15, 16]]
Why is the list being updated? Also, how can I modify case2 to get the same output as case 1?
The problem is that assignment does not make a copy in Python. You have to explicitly copy. In your own code, to copy the list, change
r_state = state
To
r_state = state[:]
Also, you will see r_state = list(state) used as well. Python 3 has the even more explicit:
r_state = state.copy()
You can also use a list-comprehension to make a new list. Here is a quick-and-dirty approach using modular arithmetic to shift the elements of your sequence:
>>> def shift_right(lst, shift):
... modulus = len(lst)
... return [lst[(i + shift)%modulus] for i in range(len(lst))]
...
>>> def right(state, index):
... return [shift_right(sub, 1) if i == index else sub for i, sub in enumerate(state)]
...
>>> test = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
>>> shift_right(test[0], 1)
[2, 3, 4, 1]
>>> shift_right(test[0], 2)
[3, 4, 1, 2]
>>> shift_right(test[0], 3)
[4, 1, 2, 3]
>>> shift_right(test[0], 4)
[1, 2, 3, 4]
>>> shift_right(test[0], 5)
[2, 3, 4, 1]
>>> right(test, 0)
[[2, 3, 4, 1], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
>>> right(test, 1)
[[1, 2, 3, 4], [6, 7, 8, 5], [9, 10, 11, 12], [13, 14, 15, 16]]
That last comprehension is perhaps a bit too dense, and could be written like this instead:
>>> def right(state, index):
... result = []
... for i, sub in enumerate(state):
... if i == index:
... result.append(shift_right(sub, 1))
... else:
... result.append(sub)
... return result
...
>>> right(test, 0)
[[2, 3, 4, 1], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
>>> right(test, 1)
[[1, 2, 3, 4], [6, 7, 8, 5], [9, 10, 11, 12], [13, 14, 15, 16]]
>>> right(test, 2)
[[1, 2, 3, 4], [5, 6, 7, 8], [10, 11, 12, 9], [13, 14, 15, 16]]
>>> right(test, 3)
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [14, 15, 16, 13]]
>>>

Split list in special chunks

I have the following problem. I have a list like:
>>> l = list(range(20))
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> # What I want:
>>> [[0, 1, 2, 3], [3, 4, 5, 6], [6, 7, 8, 9] , ...]
How can I get my list into such k pieces with length 4 in the most pythonic way? I feel like I miss something obvious here. I am fully aware of How do you split a list into evenly sized chunks? but still have no clue...
Thanks in advance!
A direct copy of an answer to question you have posted link to. The only change is the step in xrange - from n to n - 1:
def chunks(l, n):
for i in xrange(0, len(l), n - 1):
yield l[i:i + n]
list(chunks(range(20), 4))
[[0, 1, 2, 3], [3, 4, 5, 6], [6, 7, 8, 9], [9, 10, 11, 12], [12, 13, 14, 15], [15, 16, 17, 18], [18, 19]]
zip(*[iter(list(range(20)))]*4)
a = range(20)
b = [a[i:i+4] for i in xrange(0, len(a), 4)]
print b
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19]]

adaptable function to slice up nested lists?

If I have a square matrix as a nested list in python I can split it up into several equal sized boxes and create a new list where each element is a list of the numbers in one of those boxes. E.g.
a = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15 ,16]]
b = [[a[0][0], a[0][1], a[1][0], a[1][1]],
[a[0][2], a[0][3], a[1][2], a[1][3]],
[a[2][0], a[2][1], a[3][0], a[3][1]],
[a[2][2], a[2][3], a[3][2], a[3][3]]]
Is there an easier way to do this? Is there a way to set this up as a function which I can apply to matrices of different sizes and also specify the size of the boxes?
The following is equivalent to what you have and a bit more concise:
b = [a[0][:2] + a[1][:2],
a[0][2:] + a[1][2:],
a[2][:2] + a[3][:2],
a[2][2:] + a[3][2:]]
Or an equivalent list comprehension:
b = [a[i][s] + a[i+1][s] for i in (0,2) for s in (slice(None,2), slice(2,None))]
Using NumPy:
In [31]: import numpy as np
In [32]: a = np.arange(1,17).reshape(4,4)
In [33]: a
Out[33]:
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]])
In [34]: b = a.reshape(-1,2,2,2).swapaxes(1,2).reshape(4,4)
In [35]: b
Out[35]:
array([[ 1, 2, 5, 6],
[ 3, 4, 7, 8],
[ 9, 10, 13, 14],
[11, 12, 15, 16]])

Categories

Resources