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.
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 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?
I'm trying to build a python script that generates a 9x9 block with numbers 1-9 that are unique along the rows, columns and within the 3x3 blocks - you know, Sudoku!
So, I thought I would start simple and get more complicated as I went. First I made it so it randomly populated each array value with a number 1-9. Then made sure numbers along rows weren't replicated. Next, I wanted to the same for rows & columns. I think my code is OK - it's certainly not fast but I don't know why it jams up..
import numpy as np
import random
#import pdb
#pdb.set_trace()
#Soduku solver!
#Number input
soduku = np.zeros(shape=(9,9))
for i in range(0,9,1):
for j in range(0,9,1):
while True:
x = random.randint(1,9)
if x not in soduku[i,:] and x not in soduku[:,j]:
soduku[i,j] = x
if j == 8: print(soduku[i,:])
break
So it moves across the columns populating with random ints, drops a row and repeats. The most the code should really need to do is generate 9 numbers for each square if it's really unlucky - I think if we worked it out it would be less than 9*9*9 values needing generating. Something is breaking it!
Any ideas?!
I think what's happening is that your code is getting stuck in your while-loop. You test for the condition if x not in soduku[i,:] and x not in soduku[:,j], but what happens if this condition is not met? It's very likely that your code is running into a dead-end sudoku board (can't be solved with any values), and it's getting stuck inside the while-loop because the condition to break can never be met.
Generating it like this is very unlikely to work. There are many ways where you can generate 8 of the 9 3*3 squares making it impossible to fill in the last square at all, makign it hang forever.
Another approach would be to fill in all the numbers on at the time (so, all the 1s first, then all the 2s, etc.). It would be like the Eight queens puzzle, but with 9 queens. And when you get to a position where it is impossible to place a number, restart.
Another approach would be to start all the squares at 9 and strategically decrement them somehow, e.g. first decrement all the ones that cannot be 9, excluding the 9s in the current row/column/square, then if they are all impossible or all possible, randomly decrement one.
You can also try to enumerate all sudoku boards, then reverse the enumaration function with a random integer, but I don't know how successful this may be, but this is the only method where they could be chosen with uniform randomness.
You are coming at the problem from a difficult direction. It is much easier to start with a valid Sudoku board and play with it to make a different valid Sudoku board.
An easy valid board is:
1 2 3 | 4 5 6 | 7 8 9
4 5 6 | 7 8 9 | 1 2 3
7 8 9 | 1 2 3 | 4 5 6
---------------------
2 3 4 | 5 6 7 | 8 9 1
5 6 7 | 8 9 1 | 2 3 4
8 9 1 | 2 3 4 | 5 6 7
---------------------
3 4 5 | 6 7 8 | 9 1 2
6 7 8 | 9 1 2 | 3 4 5
9 1 2 | 3 4 5 | 6 7 8
Having found a valid board you can make a new valid board by playing with your original.
You can swap any row of three 3x3 blocks with any other block row. You can swap any column of three 3x3 blocks with another block column. Within each block row you can swap single cell rows; within each block column you can swap single cell columns. Finally you can permute the digits so there are different digits in the cells as long as the permutation is consistent across the whole board.
None of these changes will make a valid board invalid.
I use permutations(range(1,10)) from itertools to create a list of all possible rows. Then I put each row into a sudoku from top to bottom one by one. If contradicts occurs, use another row from the list. In this approach, I can find out some valid completed sudoku board in a short time. It continue generate completed board within a minute.
And then I remove numbers from the valid completed sudoku board one by one in random positions. After removing each number, check if it still has unique solution. If not, resume the original number and change to next random position. Usually I can remove 55~60 numbers from the board. It take time within a minute, too. It is workable.
However, the first few generated the completed sudoku board has number 1,2,3,4,5,6,7,8,9 in the first row. So I shuffle the whole list. After shuffling the list, it becomes difficult to generate a completed sudoku board. Mission fails.
A better approach may be in this ways. You collect some sudoku from the internet. You complete them so that they are used as seeds. You remove numbers from them as mention above in paragraph 2. You can get some sudoku. You can use these sudokus to further generate more by any of the following methods
swap row 1 and row 3, or row 4 and row 6, or row 7 and row 9
similar method for columns
swap 3x3 blocks 1,4,7 with 3,6,9 or 1,2,3 with 7,8,9 correspondingly.
mirror the sudoku vertical or horizontal
rotate 90, 180, 270 the sudoku
random permute the numbers on the board. For example, 1->2, 2->3, 3->4, .... 8->9, 9->1. Or you can just swap only 2 of them. eg. 1->2, 2->1. This also works.
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 :-)
In Python,
I created a 10 x 20 zero-matrix, called X:
X = numpy.zeros((10, 20))
I have another 50 x 20 matrix called A.
I want to let the 4th row of matrix X take the value of the 47th row of matrix A.
How can I write this in Python?
Note: if X is a list, then I could just write X.append () However, here X is not a list...then how can I do this?
Or, if I just have a list that contains 20 numbers, how can I let the 4th row of matrix X equal to that list of 20 numbers?
Thank you!
I'll try to answer this. So the correct syntax for selecting an entire row in numpy is
M[row_number, :]
The : part just selects the entire row in a shorthand way.
There is also a possibility of letting it go from some index to the end by using m:, where m is some known index.
If you want to go between to known indices, then we will use
M[row_number, m:n]
where m < n.
You can equate the rows/columns of a 2D-array only if they are of the same dimension.
I won't give you the exact piece of code that you'll need, but hopefully now you can figure it out using the above piece of code.
I will also suggest playing around with all kinds of matrices, and their operations like replacing some elements, columns, and rows, as well as playing with matrix multiplication until you get the hang of it.
Some useful, commands include
numpy.random.rand(m, n) # will create a matrix of dimension m x n with pseudo-random numbers between 0 and 1
numpy.random.rand(m, n) # will create a matrix of dimension m x n with pseudo-random numbers between -1 and 1
numpy.eye(m) # will create a m x m identity matrix.
numpy.ones((m, n))
And make sure to read through the docs.
Good luck! And let your Python journey be a fun one. :)