Struggling with a 3D-array append - multidimensional-array

I want to merge several 2D-arrays into a 3D one, though I keep running into problems. This is my code so far:
AMv = 2
Bz = [[1,2,3,4,5,6,7,9,8,7,6,5,4,3],[1,8,2,3,8,4,7,0,9,8],[3,6,2,3,4,5,7,8,8,7,8,7,8]]
PosVh = [2,5,9]
P = ['1', '2', '3']
MG = []
PMG = [][]
for a in range(0, len(P)):
for b in range(0, AMv):
MG.append(Bz[a][PosVh[b]:PosVh[b+1]])
# print(MG)
PMG[int(P[a])-1].append(MG)
# print(MG)
print(MG)
I have the data array 'Bz', some of the data is sorted and rearranged according to 'PosVh'. The data is correctly sorted into the new array MG. What I want now is that for each Number in P there is a new row in PMG with the data of MG.
Any ideas how I could achieve this?

In the meantime I found a solution that is almost what i want:
AMv = 2
Bz = [[1,2,3,4,5,6,7,9,8,7,6,5,4,3],[1,8,2,3,8,4,7,0,9,8], [3,6,2,3,4,5,7,8,8,7,8,7,8]]
PosVh = [2,5,9]
P = ['2', '1', '4']
MG = []
PMG = []
for a in range(0, len(P)):
MG.append([])
for b in range(0, AMv):
MG[a].append(Bz[a][PosVh[b]:PosVh[b+1]])
print(MG)
The list appears to be alright. I just want to rearrange it like this:
MG[int(P[a])-1].append(Bz[a][PosVh[b]:PosVh[b+1]])
But if I do, the array turn out to be a [3][0] array. How can that be?

Related

Given two lists(A,B) with same length, How can I find the index(i) which makes the max(sum(A[:i],B[i:]),sum(A[i:],B[:i])) smallest?

I am working on an online challenge problem, and I can solve this problem with brute force, but when the length became very large, the runtime is significantly increased, I believe there must be a better algorithm to solve this problem, but it is just out of my hand. I appreciate any brilliant ideas.
If you are allowed to use numpy, by using numpy.cumsum method you can find store sum(A[:i]), sum(A[i:]), sum(B[:i]), and sum(B[i:]) values in four different arrays as follows
import numpy as np
A = [] # Array A
B = [] # Array B
A_start_to_i = np.cumsum(A) # A_start_to_i[i] = sum(A[:i])
A.reverse() # Reverse the order
A_i_to_end = np.cumsum(A) # A_i_to_end[i] = sum(A[i:])
B_start_to_i = np.cumsum(B) # B_start_to_i[i] = sum(B[:i])
B.reverse() # Reverse the order
B_i_to_end = np.cumsum(B) # B_i_to_end = sum(B[i:])
Now all you need to do is to create sum(A[:i], B[i:]) and sum(B[:i], A[i:]) and find the index with the minimum element.
first_array = A_start_to_i + B_i_to_end # first_array[i] = sum(A[:i], B[i:])
second_array = A_i_to_end + B_start_to_i # second_array[i] = sum(B[:i], A[i:])
# Find which array has the minimum element
idx = np.argmin([min(first_array), min(second_array)])
if idx == 0:
# First array has the minimum element
i = np.argmin(first_array)
else:
# Second array has the minimum element
i = np.argmin(second_array)

Code for sorting letters of a word is not working?

For solving this question in Hackerrank,I wrote the following piece of code.It worked well on my machine, but when it was submitted,it is evaluated as a wrong answer.
T = int(input().strip())
arr = []
result = []
for i in range(T):
s = input().strip()
arr.append(s)
for item in arr:
odd = [];even = []
for value in item:
n = item.index(value)
if n%2 ==0:
even.append(value)
if n%2 == 1:
odd.append(value)
p = ''.join(even) ; q = ''.join(odd)
result.append(p + " " + q)
odd.clear();even.clear();
for value in result:
print(value)
Try this test case:
2
aaB
Baa
Your code is giving wrong results. Inner for loop is looping the characters. What if two characters are same? Your code will give wrong index number.

How to use a for loop to fill in an array by two rows at one time in R?

I want to use the data of [x] to fill in [test] based on certain sequence:
x = matrix(rnorm(330),165,2)
origins = 130:157
horizon = 8
col = 1:2
test = array(0, c(length(origins)*length(col), horizon))
for( origin in origins){
for (c in col){
test[which(origin==origins), ] = x[(origin+1):(origin+8), c]
}
}
However, this code only helps extract the second column of [x] to fill in the first 28 rows of [test]. The following picture is only a part of a complete [test] table, showing the ineffective filling from row 29 to row 56.
enter image description here
Anyone who can help me fill in them completely? Thank you very much.
Here is a possible solution, but it is still not clear what you want the result to be. better to make much smaller data and show desired result.
The left hand side of the assignment, in the original code, does not vary with c, so each time through the loop for c the same rows of test will be overwrittem,
x = matrix(rnorm(330),165,2)
origins = 130:157
horizon = 8
col = 1:2
test = array(0, c(length(origins)*length(col), horizon))
for( origin in origins){
for (c in col){
# the left hand side must vary somehow with c as well.
test[(which(origin==origins)-1) + (c - 1) * length(origins) + 1, ] = x[(origin+1):(origin+8), c]
}
}

R - Arrays with variable dimension

I have a weird question..
Essentially, I have a function which takes a data frame of dimension Nx(2k) and transforms it into an array of dimension Nx2xk. I then further use that array in various locations in the function.
My issue is this, when k == 2, I'm left with a matrix of degree Nx2, and even worse, if N = 1, I'm stuck with a matrix of degree 1x2.
I would like to write myArray[thisRow,,] to select that slice of the array, but this falls short for the N = 1, k = 2 case. I tried myArray[thisRow,,,drop = FALSE] but that gives an 'incorrect number of dimensions' error. This same issue arrises for the Nx2 case.
Is there a work around for this issue, or do I need to break my code into cases?
Sample Code Shown Below:
thisFunction <- function(myDF)
{
nGroups = NCOL(myDF)/2
afMyArray = myDF
if(nGroups > 1)
{
afMyArray = abind(lapply(1:nGroups, function(g){myDF[,2*(g-1) + 1:2]}),
along = 3)
}
sapply(1:NROW(myDF),
function(r)
{
thisSlice = afMyArray[r,,]
*some operation on thisSlice*
})
}
Thanks,
James

Push dictionary? How to achieve this in Lua?

Say I have this dictionary in Lua
places = {dest1 = 10, dest2 = 20, dest3 = 30}
In my program I check if the dictionary has met my size limit in this case 3, how do I push the oldest key/value pair out of the dictionary and add a new one?
places["newdest"] = 50
--places should now look like this, dest3 pushed off and newdest added and dictionary has kept its size
places = {newdest = 50, dest1 = 10, dest2 = 20}
It's not too difficult to do this, if you really needed it, and it's easily reusable as well.
local function ld_next(t, i) -- This is an ordered iterator, oldest first.
if i <= #t then
return i + 1, t[i], t[t[i]]
end
end
local limited_dict = {__newindex = function(t,k,v)
if #t == t[0] then -- Pop the last entry.
t[table.remove(t, 1)] = nil
end
table.insert(t, k)
rawset(t, k, v)
end, __pairs = function(t)
return ld_next, t, 1
end}
local t = setmetatable({[0] = 3}, limited_dict)
t['dest1'] = 10
t['dest2'] = 20
t['dest3'] = 30
t['dest4'] = 50
for i, k, v in pairs(t) do print(k, v) end
dest2 20
dest3 30
dest4 50
The order is stored in the numeric indices, with the 0th index indicating the limit of unique keys that the table can have.
Given that dictionary keys do not save their entered position, I wrote something that should be able to help you accomplish what you want, regardless.
function push_old(t, k, v)
local z = fifo[1]
t[z] = nil
t[k] = v
table.insert(fifo, k)
table.remove(fifo, 1)
end
You would need to create the fifo table first, based on the order you entered the keys (for instance, fifo = {"dest3", "dest2", "dest1"}, based on your post, from first entered to last entered), then use:
push_old(places, "newdest", 50)
and the function will do the work. Happy holidays!

Resources