Creating Matrices - python

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.

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']

python IndexError: list index out of range, matrix calc

I am trying to solve 1st step from Numeric Matrix Processor (hyperskill.org). I have to write program (without using numpy) which takes 2 matrix and then if number of rows and number of columns are equal I have to output sum of these 2 matrix. I know that for now number of columns is not used (only in if condition) but it doesn't matter. The problem is "IndexError: list index out of range" after I call summing function. Can someone tell me what am I doing wrong? Thx for helping!
main = []
main2 = []
final = []
mat = []
def reading():
print("rows:")
reading.rows = int(input())
print("columns:")
reading.columns = int(input())
for i in range(reading.rows):
mat = input().split()
mat = list(map(int, mat))
main.append(mat)
return main
def reading2():
print("rows:")
reading2.rows = int(input())
print("columns:")
reading2.columns = int(input())
for i in range(reading2.rows):
mat = input().split()
mat = list(map(int, mat))
main2.append(mat)
return main2
def summing():
if reading.rows == reading2.rows and reading.columns == reading2.columns:
for i in range(reading.rows):
for j in range(reading.columns):
final[i][j] = main[i][j] + main2[i][j]
print(final[j][i], end=" ")
print()
else:
print('ERROR')
reading()
reading2()
summing()

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 Initialize Matrix from input - 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()

replacing column and row with another value

Can someone please tell me why is board[x-1][y-1] == "x" not executing? I've been at this for a while now. The error I get is: TypeError: 'str' does not support item assignment. I would like to be able to place an "x" on the row and column that the player chooses.
Here's the code:
import random
board = []
for i in range(3):
board.append("|___|"*3)
for row in board:
print row
x = int(raw_input("x: "))
y = int(raw_input("y: "))
board[x-1][y-1] = "x"
One of Codecademy's exercises has a similar if not identical line of code but I don't know why mine doesn't work in this case.
board[x-1][y-1] = "x"
Board is a one dimentional list. Look at it this way:
board[0] = "|___||___||___|"
What you'd want is probably:
board[0] = ["|___|", "|___|", "|___|"]
Try this:
import random
board = []
for i in range(3):
if len(board)-1 < i: board.append([])
board[i] = []
columns = board[i]
for colNum in range(3):
columns.append('|___|')
board[i] = columns
for row in board:
print(row)
x = int(raw_input("x: "))
y = int(raw_input("y: "))
board[x-1][y-1] = "| x |"
# To verify the change:
for row in board:
print(row)
You are trying to edit a string. This is because you initialized a 1-D not 2-D list.
To initialize a 2-D list, do it as follows:
for i in range(3):
board.append(["|___|"]*3) # Note the [] around the "|___|"
When you print your board, it should look like this:
['|___|', '|___|', '|___|']
['|___|', '|___|', '|___|']
['|___|', '|___|', '|___|']
Then your code will work fine

Categories

Resources