I'm working on translating some MATLAB code to Python so I can learn MATLAB better (trying to think in terms of Python first), and I'm a bit stumped on what this block of code is doing.
n = length(a);
S = zeros(n+1,n+1);
S(1,1) = sqrt(1/b(1));
S(2,:) = (S(1,:)-[0,a(1)*S(1,1:end-1)])/sqrt(b(2));
S(3,:) = (S(2,:)-[0,a(2)*S(2,1:end-1)]-[0,0,sqrt(b(2))*S(1,1:end-2)])/sqrt(b(3));
S(4,:) = (S(3,:)-[0,a(3)*S(3,1:end-1)]-[0,0,sqrt(b(3))*S(2,1:end-2)])/sqrt(b(4));
I understand the first 2 lines (create a n+1 by n+1 matrix S), but I'm having trouble understanding the next 3.
From what I understand (n:m) is Matrix lookup notation. So, S(1, 1) means the value at 1st row, first column, which is set to 1/math.sqrt(b[0]) in terms of Python. This would mean that in our matrix S, the first row is an array who 1/math.sqrt(b[0]), and the rest are 0's, right?
For the 4th line, I'm having real trouble understanding the vode. Are we saying the 2nd row is the 1st row minus an array from 0 to a(1)*S(1,1:end-1)? What exactly does a(1)*S(1,1:end-1) represent here?
I see that the next 2 lines is a recurrence relation based on j-1th and j-2th row for some j >= 3 (2 if Python), but I have very little idea as to what the recurrence relation is computing.
Any help "translating" this code to Python (in terms of pseudocode for understanding, not actual hard code) would be tremendously helpful, as learning MATLAB has been pretty tricky so far for me. Thank you.
I'll use some dummy values and try to explain clearly what's going on in the code. Also I'm definitely not an expert in matlab and my knowledge of it is regulated to a first-year programming course in university so do take what I write with a pinch of salt!
Let us define:
a = [1,2,3,4]
b = [1,2,3,4]
Yes, line three S(1,1) = sqrt(1/b(1)); would indeed result in the following array where the value of (0,0) in python is 1 divided by the square root of the first value in list b or math.sqrt(1/b[0]) like you defined.
1 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
Line four S(2,:) = (S(1,:)-[0,a(1)*S(1,1:end-1)])/sqrt(b(2)); has several things going on at once so let's work through it step by step.
S(1,:) refers to the entire 1st row of array S.
a(1)*S(1,1:end-1) is an array where it is the first item of array
a(1) = 1 multiplied by the 1st row of array S up till the second
last item in the row S(1,1:end-1) = 1 0 0 0.
[0,a(1)*S(1,1:end-1)] is an array where the 1st item is 0 and the
2nd item is the array a(1)*S(1,1:end-1). Hence [0,a(1)*S(1,1:end-1)] = 0 1 0 0 0
S(1,:)-[0,a(1)*S(1,1:end-1)] is just having that entire first row of array S(1,:) = 1 0 0 0 0 subtracted by the array [0,a(1)*S(1,1:end-1)] = 0 1 0 0 0 which gives us 1 -1 0 0 0
Finally we divide everything by sqrt(b(2)) = 1.4142
This gives us S(2,:) = 0.7071 -0.7071 0 0 0
Lines five and six are similar to line four but with some changes to which indexes are being manipulated.
It's not pseudocode like you asked for but I hope my answer helps you to some degree. While you're working on this, you might want to check out this paper which I found rather helpful with regards to understanding arrays in Matlab
MATLAB array manipulation tips and tricks
For line 3, you are right!
For line 4, a(1)*S(1,1:end-1) means a(1) times a list that consists of the 1st to the last 2nd element of S(1,:). For example, if S(1,:) = [1, 2, 3, 4, 5] then a(1)*S(1,1:end-1) means a(1)*[1, 2, 3, 4]. You can think of end-1 is equivalent to len(S[0]) - 1 in python. The translation of line 4 in python is:
temp = [0] + [a[0]*i for i in S[0][0:-1]]
for i in range(len(S[0])):
S[1][i] = (S[0][i] - temp[i]) / math.sqrt(b[1])
Based on the 4th line, can you translate 5th and 6th lines?
Related
I'm trying to compare these specific elements to find the highest number:
Q_2 = [[5,0,41],[6,3,5],[7,4,3],[8,5,40]]
This is my 2d array in Python I want to compare Q_2[i][2] with each other the example is that number 41 gets compared to 5 and 3 and 40 and the result is the highest number.
I came up with 2 ways:
I store the Q_2[i][2] of the every item to a new list (which I don't know why it wont)
Or I do a loop to compare them
from array import *
#These 2 are used to define columns and rows in for other 2d arrays (All arrays have same column and row)
n = int(3)
m = int(input("Enter number of processes \n")) #I always type 4 for this variable
Q_2 = [[5,0,41],[6,3,5],[7,4,3],[8,5,40]]
for i in range(m):
for j in range(1,3,1):
if(Q_2[i][2]>=Q_2[j][2]:
Max_Timers = Q_2[i]
print(Max_Timers) #to check if the true value is returned or not
The result it returns is 40
This worked when the 0 index was lower then others but once I changed the first one to 41 it no longer works
there is no need of two 'for' loops, as your are after just one element from a 2D array rather than complete 1D array.
This is a working code on 2D array, to get the 1D array that got the highest element on index-2:
max_index = 0
Q_2 = [[5,0,41],[6,3,5],[7,4,3],[8,5,40]]
for i in range(len(Q_2)):
if(Q_2[i][2]>=Q_2[max_index][2]):
max_index = i
print(Q_2[max_index])
The reason your code doesn't work can be easily found out by working out a dry run using the values you are using.
According to your logic,
number 41 gets compared to 5 and 3 and 40 and the result is the highest number
and this is achieved by the two for loops with i and j. But what you overlooked was that the max-value that you calculated was just between the current values and so, you are saving the max value for the current iteration only. So, instead of the Global maximum, only the local/current maximum was being stored.
A quick dry-run of your code (I modified a few lines for the dry-run but with no change in logic) will work like this:
41 is compared to 5 (Max_Timers = 41)
41 is compared to 3 (Max_Timers = 41)
5 is compared to 3 (Max_Timers = 5)
40 is compared to 5 (Max_Timers = 40)
40 is compared to 3 (Max_Timers = 40)
>>> print(Max_timers)
40
So, this is the reason you are getting 40 as a result.
The solution to this is perfectly mentioned by #Rajani B's post, which depicts a global comparison by storing the max value and using that itself for comparison.
Note: I didn't mention this above but even when you used a 2nd for loop, which was already not required, there was an even less reason for you to use a range(1,3,1) in the 2nd loop. As you can see in the dry-run, this resulted in skipping a few of the checks that you probably intended.
You can use numpy to significantly simplify this task and for performance as well. Convert your list into an np.array(), then select the column of interest, which is Q_2[:,2] and apply numpy's .max() method.
import numpy as np
Q_2 = [[5,0,41],[6,3,5],[7,4,3],[8,5,40]]
Q_2 = np.array(Q_2)
mx2 = Q_2[:,2].max()
which gives the desired output:
print(mx2)
41
I'm working on my first game with Python and Pygame, and I have to create a binary puzzle.
I'm facing a problem generating a solved grid with these conditions:
Each box should contain either a zero or a one.
More than two equal numbers immediately next to or below each are not allowed.
Each row and each column should contain an equal number of zeros and ones.
Each row is unique and each column is unique. Thus, any row cannot be exactly equal to another row, and any column cannot be exactly equal to another column.
I tried somthing like
parents = []
unique_found = False
while not unique_found:
candidate_array = np.random.choice([0, 1], size=(CELL,CELL))
if not any((candidate_array == x).all() for x in parents):
[(i, j) for i, j in enumerate(candidate_array)]
unique_found = True
parents.append(candidate_array)
It's generating a random grid of one and zeros:
[[0 0 0 1 0 1]
[1 0 0 1 1 1]
[0 0 0 0 1 0]
[1 0 0 0 1 0]
[0 1 1 1 1 1]
[0 1 1 0 1 1]]
but I don't know how to add the conditions I want to make this grid less random.
For a direct solution, there's basically no way to get around coding up those constraints. Once you do code them up, try backtracking: try putting a 0 in the first cell and check the constraints. If the constraints are satisfied, recursively step to the next cell and try a 0 there.
If a constraint is ever breached and you've tried all of the possible values on a square, one of the assumptions somewhere along the way must have been invalid, so undo the most recent 0 or 1 placed, pop the call stack and backtrack to the previous index to try the next possible value. This backtracking might unwind all of the moves, but eventually it'll hone in on a solution if a board is solvable. It's brute force with the optimization that it stops exploring impossible positions.
This is basically the same as the most straightforward way of solving Sudoku, but with different constraints and different values per square (much fewer, but more squares). The only difference between generating a solved board from scratch as you're doing and solving one with a few pre-filled values is that you skip the squares with pre-filled values. It's a trivial difference. Check out this gif which illustrates the backtracking algorithm working.
Looking into Sudoku solving can offer deeper ideas for domain-specific improvements you could apply to this puzzle to gain a speed increase, once you have a basic backtracking approach working. Even without any domain-specific knowledge, the backtracking approach can be multithreaded/multiprocessed for a speed increase, with each worker starting from a specific configuration of the first few top-level values for the first squares at the the root of the search.
By the way, following this method is deterministic on an empty board, so you'll get the same filled board every time. You could randomize the choices along the way, or even the order of visiting squares, if you want a non-deterministic result.
You can improve the backtracking approach by permuting a pre-filled grid that satisfies constraint 3 (equal numbers of 0s and 1s per row/column), but it's still basically backtracking (the granularity of a stack frame changes -- now it's a possible configuration of a row rather than a cell), and is purely an optimization, so I'd start with the cell-by-cell approach.
That said, I'd avoid blindly generating and testing random configurations. It's not much easier to code than backtracking, because you still need to code up and check all of the constraints, and a non-systematic approach would likely take much longer to find a solution than a systematic one.
If you're open to using external tools, you can add the constraints to an off-the-shelf constraint solver like PuLP or Z3 and it'll spit the answer out.
You could create initial solution like the one below which only satisfies condition 1 and 3.
[1 ,1, 1, 0, 0 ,0]
[1 ,1, 1, 0, 0 ,0]
[1 ,1, 1, 0, 0 ,0]
[0 ,0, 0, 1, 1 ,1]
[0 ,0, 0, 1, 1 ,1]
[0 ,0, 0, 1, 1 ,1]
And then swap rows and columns randomly.
As those wouldn't break the third condition.
The idea would then be to swap rows or columns until you hit a valid solution.
Need to start off by saying that this is essentially a homework question and it’s really a tough one for me.
From the print output of a dynamic matrix (or anything that can be formatted and printed to be visually similar), I need to use indexing from a user’s input to change values in that “matrix”. It doesn't have to be a matrix, something that can be formatted to be similar would also work.
What makes this problem hard for me is that only un-nested lists, strings, or dictionaries can be used, and importing packages is not allowed. So, list comprehension is out of the question.
One thing I’ve tried so far is to print separate lists and index based on separate lists but I got stuck.
You can use a 1D list, take x, y coordinates in user input and convert the y coordinate in terms of x offsets.
For example, say you want to represent a 5x3 array and the user wants the second column (x=2) and third row (y=3). Let's assume our matrix displays with 1,1 being top left corner.
Multiply the y coordinate minus 1 by the width of the matrix to obtain the number of cell offsets in your 1D-list, then further offset by x - 1 (remember, Python lists are 0-based) to position correctly on the x-axis.
Example of matrix with 1D-based indices:
0 | 1 | 2 | 3 | 4
5 | 6 | 7 | 8 | 9
10 | 11 | 12 | 13 | 14
Taking the algorithm above:
index = (y - 1) * 5 + x - 1 # ((3 - 1) * 5 + 2 - 1) = 11
As you can see, 11 is indeed in our matrix the second column and third row, as per the example user inputs.
You can then display the matrix by way of a simple for loop, knowing the size of the matrix and inserting a new line as appropriate.
You may simplify the above a bit if the user is requested to input 0-based indices as well. You will not need to substract 1 from x and y.
Let's say I have a really long array like this:
arr = np.array([0,0,1,1,0,1,1,1,0,0,0,1,1,0,0,1]}
I also have a maximum position where I can look, like 6, making a slice of the array that returns this:
sliceLocation = 6
returning:
np.array([0,0,1,1,0,1,1]}
now I want to write a piece of code that slices the array and then searches for the first 0 inside this array coming from the back, in this case returning 4 as a viable position in a quick and efficient time. Can anybody help me?
Here is your example but i dont understand what you want to do with the rest of the array arr.
arr = np.array([0,0,1,1,0,1,1,1,0,0,0,1,1,0,0,1])
sliceLocation = 6
arr = arr[:sliceLocation+1]
idx = np.where(arr==0)[0][-1]
idx = 4
The following should work:
sliceLocation = 6
sliceLocation-list(arr)[:sliceLocation+1][::-1].index(0)
4
How it works: It slices the array, changes it to a list, reverses it, find the index of first 0 and by subtracting it from sliceLocation it gives the final result
I'm very new at this and have to do this for a project so keep that in mind.
I need to write a function sumOfDiagonal that has one parameter of type list.
The list is a 4x4 2-dimensional array of integers (4 rows and 4 columns of integers).
The function must return the sum of the integers in the diagonal positions from top right to bottom left.
I have not tried anything because I have no idea where to begin, so would appreciate some guidance.
Since you haven't specified a language (and this is probably classwork anyway), I'll have to provide pseudo-code. Given the 4x4 2d array, the basic idea is to use a loop specifying the index, and use that index to get the correct elements in both dimensions. Say we had the array:
[][0] [][1] [][2] [][3]
----- ----- ----- -----
[0][] 1 2 3 4
[1][] 5 6 7 8
[2][] 9 10 11 12
[3][] 13 14 15 16
and we wanted to sum the top-left-to-bottom-right diagonal (1+6+11+16)(1). That would be something like:
def sumOfDiagonal (arr, sz):
sum = 0
for i = 0 to sz - 1 inclusive:
sum = sum + arr[i][i]
return sum
That's using the normal means of accessing an array. If, as may be given the ambiguity in the question, your array is actually a list of some description (such as a linked list of sixteen elements), you'll just need to adjust how you get the "array" elements.
For example, a 16-element list would need to get nodes 0, 5, 10 and 15 so you could run through the list skipping four nodes after each accumulation.
By way of example, here's some Python code(2) for doing the top-left-to-bottom-right variant, which outputs 34 (1+6+11+16) as expected:
def sumOfDiagonals(arr):
sum = 0
for i in range(len(arr)):
sum += arr[i][i]
return sum
print(sumOfDiagonals([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]))
(1) To do top right to bottom left simply requires you to change the second term into sz - i - 1.
(2) Python is the ideal pseudo-code language when you want to be able to test your pseudo-code, provided you stay away from its more complex corners :-)