How to Initialize Matrix from input - Python - python

i need to implement a program that initialize matrix with input elements and will print the matrix in rows and columns, any ideas?
def initializeMatrix(m):
rows = 2
columns = 2
for x in range(rows):
for y in range(columns):
num = input('Insert Number: ')
m.append(num)
print(m)

Assuming your matrix m is initialized with your code, which is correct.
for a in range(rows):
for b in range(columns):
print(m[a*columns + b], " ", end='')
print()
What's more, your approach is better than using a list of lists since in your case the values of a matrix will be held in a contiguous block of memory, thus providing faster access to them.
Edit regarding your latest comments
Certainly, you can initialize a list of lists like this:
rows=2
columns=2
m=[]
for a in range(rows):
m.append(list())
for b in range(columns):
m[a].append(input("Enter a number: "))
Then you output it like this:
for row in m:
for number in row:
print(number," ", end="")
print()

Related

How can I create a matrix in which the user inputs both rows and columns and then enters the values for each position in Python?

This should be how the code works:
n = int(input()) #number of rows, for example 3
m = int(input()) #number of columns, for example 5
Then the user is going to enter a value for a row followed by a value for column.
x = int(input()) #This should be the row number, for example row 1
y = float(input()) #This should be the value for each position inside of each x.
Both x and y need to follow certain conditions so I have them apart. In theory it should look something like this:
matrix = [ [0.4], [0.3, 0.2, 0.5], [0.7] ] #Row 1 has 1 float, Row 2 has 3 float and Row 3 only 1
Some floats are going to enter on different rows, like row 1 can have three floats from the input, and another row (row 3) could have 5 floats from the input.
I have tried using the following loop:
for i in range(n): #I have tried multiple ways using len function, append function, etc.
for j in range(m):
But I can't seem to be able to assign each value on the matrix as I have to make sure that the inputs follow certain conditions as the program should read as many different floats as te variable "m" goes.
The reason why I am elaborating the code this way is because I have to calculate an average (in a different function) based on the different values that I get from the float input, making them go through a formula that I already had done before.
From what I understand, this should be roughly what you need:
row_input_count = int(input("please enter the number of rows you want to input: "))
column_count = int(input("please enter the number of columns: "))
matrix = []
for _ in range(row_input_count):
row_index = -1
while row_index < 0:
row_index = int(input(f"please select a row: "))
matrix = matrix + [[0] * column_count] * (row_index + 1 - len(matrix))
values = [0] * (column_count + 1)
while len(values) > column_count:
value_string = input(f"please input up to {column_count} values for row {row_index}: ")
values = [float(x) for x in value_string.split()]
values = values + [0] * (column_count - len(values))
matrix[row_index] = values
print("The resulting matrix: [")
for row in matrix:
print(row)
print("]")
Does this help you understand how the parts you already figured out could work together? I think it should be all relatively easy to read. Python's syntax for repeating elements in a list might be a bit strange to get used to:
>>> ["hi"] * 3
['hi', 'hi', 'hi']

Diagonal shape in Python using while loops

I am working on a basic shapes program in Python and can't seem to work out my code. I need to keep it simple using while loops and the variables given, nested loops are usable.
Here is my code for a square:
def drawSquare(size, drawingChar):
print('Square: ')
row = 1
while row <= size:
# Output a single row
drawRow(size, drawingChar)
# Output a newline to end the row
print()
# The next row number
row = row + 1
print()
It is supposed to print like:
x
x
x
x
based on a size and character entered by the user.
drawRow is another function similar to drawSquare:
def drawRow(size, drawingChar):
col = 1
while col <= size:
print(drawingChar, end=' ')
col = col + 1
It would make more sense with a for loop:
def drawSquare(size, drawingChar):
for i in range(size):
print(" "*i + drawingChar)
Example:
drawSquare(4, "p")
Output:
p
p
p
p
Please show your work for drawDiagonal (or anything) when asking a question.
Diagonal is probably the easier case here:
def drawDiagonal(size, drawingChar):
for y in range(size):
s = ' '* y + drawingChar
print(s)
drawDiagonal(4,"X")
X
X
X
X
(Maybe pick a fixed font)
The solution I came up with is:
def drawDiagonal(size, drawingChar):
print('Diagonal: ')
row = 1
while row <= size:
# Output a single row
drawRow(row - 1, ' ')
print(drawingChar)
# Output a newline to end the row
print()
# The next row number
row = row + 1
print()
Note: drawRow is defined separately (above, in question)
& drawDiagonal was called separately as well:
drawDiagonal(userSize, userChar)
where
userSize = input('Size: ')
userChar = input('Character: ')

How to display number sequences in rows and columns in Python 3?

I have a coding assignment to input row and column length, and create a power table. THe example below is for 5 rows, 5 columns.
The code I have so far prints the correct number of rows and columns, but I haven't been able to get the calculations to work. It just shows a table of 1's, five by five.
rows = int(input("Enter a number of rows: "))
cols = int(input("Enter a number of columns: "))
x = 1
y = 1
z = 1
line = ""
while x <= cols :
line = line + format(y**cols, "4d")
x = x + 1
while z <= rows :
print(line)
z = z + 1
The basic problem is that you need to nest your loops. Your second problem is that you never change y. What you do at the moment is to compute the power sequence for 1 into five different lines -- and then you print that last line only five times. Try two changes:
Compute a line, then print it immediately. Then you go to the next line.
Use the correct variable.
After changes:
while z <= rows:
while x <= cols:
line = line + format(x**cols, "4d") # Note the variable change
x = x + 1
print(line)
z = z + 1
Also, look up the for statement, as this will simplify things. After that, look up list comprehension for even more compression.
Here is a way to do it that preserves padding no matter what:
def grid(rows, cols, padding):
max_num_len = len(str(rows**cols))
return '\n'.join([
''.join(['{{:>{}}}'.format(max_num_len+padding).format((row+1)**(col+1))
for col in range(cols)])
for row in range(rows)
])
print(grid(5, 5, 3))
Instead, try creating a 2D array in Python such as a 2D list.
Matrix = [[0 for x in range(5)] for y in range(5)]
for i in range(5):
for j in range(5):
Matrix[i][j]=j^i
Then, print the data you need using nested for loops.
for i in range (5):
for j in range(5):
print(Matrix[j][i])

How to change values in nested list python

The matrix represents cell points. If we imagine these cell points being a grid, we need to make the values within the matrix equal to the input T1 in quadrants 2 and 4 and the values input T2 for quadrants 1 and 3. As in, from row 0 to 2 and column 0 to 3 it should be the value T1. Also, I need to make this appear as cells, with lines in between all rows/columns.
#input values needed
A = input("Enter a value for the first heater/cooler temp: ")
B = input("Enter a value for the second heater/cooler temp: ")
T1 = input("Enter a value for the first initial plate temp: ")
T2 = input("Enter a value for the second initial plate temp: ")
#the stabilizing criterion value
matrix = []
for row in range(0,6):
matrix.append([])
for column in range(0,9):
matrix[row].append(column)
for row in matrix:
print(row)
In this code, row in range(0,6) refers to all positions of the matrix that are in the first row, then second, and so on. It loops over all the rows.
So matrix[0][x] refers to all the positions in the 0th row (and you can access each position by setting x = 1, 2, ...).
What you want to do, is set values to T1 for a specific set of rows and columns, right?
Since you are anyway looping through all the rows and columns, you can check if at any point, the combination of row and column falls in the desired range:
if row < 3 and column < 4:
matrix[row][column] = T1
What this does is, whenever the combination of row and column numbers falls in the range that is, row = 0 to 2 and column = 0 to 3, it sets the value at those positions in the matrix, to T1.
Does this answer your question?
Now about the printing part, you can try a function like this:
def printy(P):
for i in range(len(P[0])):
print '---',
print
for i in range(len(P)):
for j in range(len(P[0])):
print P[i][j], '|',
print
for i in range(len(P[0])):
print '---',
print

Creating Matrices

I'm trying to create a game of Minesweeper on python3 and the first thing im trying to do is have the user use command line input for the number of rows and columns that they wish to play with. Then I want to create a matrix based on those two numbers, but with the code below it keeps printing those two numbers that the user inputs instead of creating the actual matrix
import sys
def mineBoards(m):
Rows = len(m)
Cols = len(m[0])
for r in range(0,Rows,1):
for c in range(0,Cols,1):
print (m[r] [c],end="")
print()
return
def main():
Rows = input(int(sys.argv[1]))
Cols = input(int(sys.argv[2]))
main()
This is what I would do:
def make_board(rows, columns):
board = []
for i in range(rows):
board.append([])
for j in range(columns):
board[i].append(“-“)
return board
number_of_rows = int(input(“Number of rows: “))
number_of_cols = int(input(“Number of columns: “))
game_board = make_board(number_of_rows, number_of_cols)
Hope this helps!
You can do it like this:
rows = int(input("Number of rows: "))
cols = int(input("Number of columns: "))
board = [['-' for x in range(cols)] for y in range(rows)]
After that, the board will be a list of lists with dimensions rows x cols.
You can of course substitute the '-' with anything else, this is just an example.

Categories

Resources