As a newbie to python, I've come across a task that I'm having trouble completing. I am supposed to create a new matrix, taking into consideration the original one, inputted by the user, where each element corresponds to the number of adjacent elements greater or equal to the corresponding one in the original matrix. Since English is not my native language, I might not have presented it properly so here is an example:
input:
3x3 matrix
9 14 13
3 0 7
8 15 15
output:
3x3 matrix
2 5 2
1 0 1
2 5 3
So, if it isn't clear, the new matrix determines how many adjacent elements are greater or equal to an element in the original one. 9 is greater than 3 & 0, so that results in "2", 14 is greater than all the adjacent ones so it prints out "5", etc... It also takes diagonals into consideration, of course.
So far, I've got down the input of the original matrix but I'm unsure how to proceed further. I am not someone who's got access to university materials, professors or peer help and my experimentation and search online has been futile so far. I do not need a complete solution, rather than pointers and concept explanation.
This is the code so far:
# matrix input
rOne = int(input("Number of rows:"))
cOne = int(input("Number of columns:"))
# initialize matrix
matrixOne = []
print("Enter elements rowwise:")
# user input
for i in range(rOne): # for loop za redove
a =[]
for j in range(cOne): # for loop za kolone
a.append(int(input()))
matrixOne.append(a)
# print matrix one
for i in range(rOne):
for j in range(cOne):
print(matrixOne[i][j], end = " ")
print()
Here is a function that can do the exact thing:
def adj_matrix(matrixOne, rOne, cOne):
new_lst = []
for i in range(rOne):
a = []
for j in range(cOne):
count = 0
x, y = (i, j) # matrix values here
cells = list(starmap(lambda a,b: (x+a, y+b), product((0,-1,+1), (0,-1,+1)))) # this will find all the adjacent index
filtered_cell = [p for p in cells if (sum(p)>=0 and prod(p)>=0)] # this filters out all the negative indexs
filtered_cell = [p for p in filtered_cell if p[0]<rOne and p[1]<cOne] # this filters out index that are greater than matrix
for z in filtered_cell:
if matrixOne[i][j] >= matrixOne[z[0]][z[1]]:
count += 1
a.append(count-1)
new_lst.append(a)
return new_lst
also import:
from itertools import product, starmap
from math import prod
Actually managed to solve the thing, feels amazing :D
def get_neighbor_elements(current_row, current_col, total_rows, total_cols):
neighbors = []
for i in [-1, 0, 1]: # red pre, isti red, red posle
for j in [-1, 0, 1]: # kolona pre, ista kolona, kolona posle
row = current_row + i
col = current_col + j
if row < 0 or col < 0 or row >= total_rows or col >= total_cols: # preskace se ako se izaslo iz granica matrice
continue
if row == current_row and col == current_col:# ako su red i kolona isti, preskace se(to je taj isti element)
continue
neighbor = [row, col]
neighbors.append(neighbor)
return neighbors
def make_new_matrix(old_matrix):
new_matrix = []
for i in range(len(old_matrix)):
new_matrix.append([])
for i in range(len(old_matrix)): # iteriramo kroz redove stare matrice
for j in range(len(old_matrix[i])): # iteriramo kroz kolone stare matrice
neighbors = get_neighbor_elements(i, j, len(old_matrix), len(old_matrix[i])) # dobavljamo komsije
count = 0
for neighbor in neighbors: # sad gledamo da li je trenutni element veci ili jednak susednim
if old_matrix[i][j] >= old_matrix[neighbor[0]][neighbor[1]]:
count += 1
new_matrix[i].append(count)
return new_matrix
def print_matrix(matrix):
for i in range(len(matrix)):
for j in range(len(matrix[i])):
print(str(matrix[i][j]) + " ", end='')
print()
if __name__ == '__main__':
matrix = [[12, 10], [2, 10]]
print("Old matrix: ")
print_matrix(matrix)
new_matrix = make_new_matrix(matrix)
print("New matrix")
print_matrix(new_matrix)
So, maybe this question will sound very beginnerish, but I just don't know how I should begin with this example:
So the example is:
I have a list for example 13 items long (1,2,3,4...13)
There's a given number, let's say 6
The program needs to show me in a list, in what order are the numbers going to fall out. If the second number is 6, it means every time the sixth item is the next whcih is going to fall out. But my problem is that how could I tell python that if the index number goes up too high, it should start counting again from the beggining?
This is what I made myself so far
x = int(input("Number of items (numbers): "))
y = int(input("Fall-out number: "))
#n = 1
#id = 0
numbers = [n for n in range(x+1)]
fallsout = []
numbers.remove(30)
for i in numbers:
if i % y == 0:
fallsout.append(i)
print (numbers)
print (fallsout)
Here's an example what should be in the input and output:
Input:
x = 13
y = 6
Output: 6 12 5 13 8 3 1 11 2 7 4 10 9
Okay, looks like you want to copy every 6th element from numbers into fallout and then remove the element from numbers, and continue on in a cyclic fashion until numbers is empty.
import copy
x = int(input("Number of items (numbers): "))
y = int(input("Fall-out number: "))
# list should start from 1 as by the example
numbers = [n for n in range(1,x+1)]
# deep copy to preserve original list
numbers_copy = copy.deepcopy(numbers)
fallsout = []
count = y
while len(numbers_copy)!=0:
fallsout.append(numbers_copy[count-1])
# remove element
del numbers_copy[count-1]
# handle starting edge
if count == 0:
count = 1
# handle last edge
if numbers_copy != []:
count = (count+y-1)%len(numbers_copy)
print numbers
print fallsout
Output is
Number of items (numbers): 13
Fall-out number: 6
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
[6, 12, 5, 13, 8, 3, 1, 11, 2, 7, 4, 10, 9]
Explanation:
Suppose I have a array numbers = [1,2,3,4,5,6] of length=6, and I am using an counter "count" to iterate through the list. So that,
numbers[count] = 2 (when count=1)
Then to look at the next element, I would use numbers[count+1].
To jump back to the starting of the list, we use modulus operation,
count = (count+number_of_steps)%len(numbers)
eg, at index=4 and to jump 3 steps, next index would be (4+3)%6 = 1
Now we have to copy every yth element from the list,so we use,
fallsout.append(numbers_copy[count-1]) # count-1 as we are counting from 0
Then we remove that number from the list,
del numbers_copy[count-1]
Then we jump forward count by y steps by modulus as discussed above,
count = (count+y-1)%len(numbers_copy) # again -1 as we count from 0
The length of numbers needs to be calculated again as the list could change due to deleting of elements.
I'm working on an assignment for my CIS class in python. We have to code a Sudoku checker. In a 9x9 board we obviously have to check each row, col and 3x3 square for duplicates. I'm a little stuck on the idea of how to check the numbers by a 3x3 square. Below is my code for checking each row and col, if someone could help me a little with an outline or an approach just something for checking each 3x3 square that would be amazing!
self.columns = [ ]
for col in range(9):
col_tiles = [ ]
self.columns.append(col_tiles)
for row in range(9):
col_tiles.append(self.tiles[row][col])
self.squares = [ ]
for col in range(1, 10, 3):
for row in range(1, 10, 3):
square_tiles = [ ]
self.squares.append(square_tiles)
for x in range(3):
for y in range(3):
square_tiles.append(self.tiles[x][y])
This assumes you have the freedom to read the data and structure how you want. We want a set of unique values 1-9 for each row/column/3x3 grid, so one way is to either use a set or a list comparison (we'll use set here to make it cleaner). If we create a set equal to the numbers from 1 to 9, we have a point against which we can compare all of our other groups. Assume a structure like this (from here):
In [1]: r1 = [9,3,2,5,4,8,1,7,6]
In [2]: r2 = [1,8,7,9,2,6,5,4,3]
In [3]: r3 = [5,4,6,3,7,1,2,8,9]
# Continues....
Where each row represents a full row of data. Now lets create a section of that data that represents the first three rows, pull out one grid and compare the contents to our set:
In [4]: sec1 = [r1, r2, r3]
In [5]: nums = set(range(1, 10))
In [6]: nums == set(n for row in sec1 for n in row[:3])
Out[6]: True
This iterates over the first three rows and returns the first three elements in each of those rows. To get a better visual, here is the equivalent for-loop code to make it a bit easier to decipher:
result = set()
for row in sec1:
for n in row[:3]:
result.add(n)
Since our set of numbers includes everything from 1-9, we know it is valid. To move to the second, we range the row[:3] to row[3:6] (and row[6:9] after that). You'll then need to handle this for the next two sections as well. I'll leave it to you as to how to wrap this in a more dynamic structure (note the multiples of three), but hopefully this will get you started :)
Whenever you're having trouble coming up with an algorithm, just ask yourself: "How would I solve this manually, if the only way I could be given the problem was by a computer".
In other words, if I asked you to check the top left 3x3 grid, your eyes would just go to the top left corner and add up numbers. But if I said, check the top left 3x3 grid, and didn't actually give you the board, you'd say, "OK, give me the top left 3x3 grid".
And I'd say "How?"
And you'd say, "Imagine the tiles are numbered by rows and columns. I want the tiles in spots (0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), and (2,2)"
Does that help?
Here's what I would do: create 3 dictionaries, one for the rows, one for the columns, and one for the 3x3 squares.
while you loop through each element in the sudoku puzzle, keep track of your row and column (trivial), and use if statements to keep track of which 3x3 square you're in (a bit more involved)
then just send each element to the corresponding row, column, and 3x3 square dictionary, and compare at the end.
This way you only need to inspect each element once.
EDIT: also, set will probably be useful
This function will do. "sample" gives the randomness, so every time you run this you will get a different one.
from random import sample
def generate_sudoku_checker():
random_list = sample([1,2,3,4,5,6,7,8,9],9)
random_list = random_list + random_list[:9]
for i in range(3):
for j in range(3):
print(random_list[i+j*3:i+j*3+9])
Here is my solution to this :
Funtion:
def check_sudoku(lis):
n = len(lis)
digit = 1 #start from one
while (digit<=n):
i=0
while i<n: # go through each row and column
row_count=0
column_count=0
j=0
while j < n: # for each entry in the row / column
if lis[i][j] == digit: # check row count
row_count = row_count+1
if lis[j][i]== digit :
column_count = column_count+1
j=j+1
if row_count !=1 or column_count!=1:
return False
i=i+1 # next row/column
digit = digit+1 #next digit
return True
Late to the party but this worked for me:
def insert_sudoku():
puzzle = []
for i in range(9):
print("You've entered", len(puzzle), "rows so far")
row = input("Enter a row")
if len(row) < 9:
print("Not enough numbers on this row")
return insert_sudoku()
elif len(row) > 9:
print("Too many numbers. Try again!")
return insert_sudoku()
try:
row = [int(dig) for dig in row]
puzzle.append(row)
except:
print("Whoops, looks like you didn't enter only numbers somewhere. Try again!")
return insert_sudoku()
validate_entries(puzzle)
def validate_entries(puzzle):
check = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b1, b2, b3, b4, b5, b6, b7, b8, b9 = [], [], [], [], [], [], [], [], []
for i in range(9):
z = []
for x in range(9):
z.append(puzzle[i][x])
puzzle.append(z)
for i in range(3):
b1 += (puzzle[i][:3])
b4 += (puzzle[i][3:6])
b7 += (puzzle[i][6:])
for i in range(3,6):
b2 += (puzzle[i][:3])
b5 += (puzzle[i][3:6])
b8 += (puzzle[i][6:])
for i in range(6,9):
b3 += (puzzle[i][:3])
b6 += (puzzle[i][3:6])
b9 += (puzzle[i][6:])
puzzle.append(b1)
puzzle.append(b2)
puzzle.append(b3)
puzzle.append(b4)
puzzle.append(b5)
puzzle.append(b6)
puzzle.append(b7)
puzzle.append(b8)
puzzle.append(b9)
for iter in puzzle:
if sorted(iter) != check:
print("No")
return
print("Yes")
insert_sudoku()
Inspired by this article
EDIT: Indentation might be off from copy + pasting the code.
What my answer adds is the use of a list comprehension to extract the tiles from the board.
"""
# good
board=[
[2,9,5,7,4,3,8,6,1],
[4,3,1,8,6,5,9,2,7],
[8,7,6,1,9,2,5,4,3],
[3,8,7,4,5,9,2,1,6],
[6,1,2,3,8,7,4,9,5],
[5,4,9,2,1,6,7,3,8],
[7,6,3,5,2,4,1,8,9],
[9,2,8,6,7,1,3,5,4],
[1,5,4,9,3,8,6,7,2]
]
"""
# bad
board = [
[1,9,5,7,4,3,8,6,2],
[4,3,1,8,6,5,9,2,7],
[8,7,6,1,9,2,5,4,3],
[3,8,7,4,5,9,2,1,6],
[6,1,2,3,8,7,4,9,5],
[5,4,9,2,1,6,7,3,8],
[7,6,3,5,2,4,1,8,9],
[9,2,8,6,7,1,3,5,4],
[2,5,4,9,3,8,6,7,1]
]
def check(l):
# each digit 1-9 should occur once
for n in range(1,10):
try:
l.index(n)
except ValueError:
return False
return True
# check the rows
for row in board:
print(check(row))
# check the columns
for column in [ [ board[r][c] for r in range(9) ] for c in range(9) ]:
print(check(column))
# check the tiles
for tile in [[board[r][c] for r in range(row, row + 3) for c in range(col, col + 3)] for row in range(0, 9, 3) for col in range(0, 9, 3)]:
print(check(tile))
This is my solution. I also want to confirm the time and space complexity of this code:
"""
Sample input 1:
295743861
431865927
876192543
387459216
612387495
549216738
763524189
928671354
154938672
Output: YES!
Sample input 2
195743862
431865927
876192543
387459216
612387495
549216738
763524189
928671354
254938671
Output: NOPE!!
"""
##################Solution############################################
def get_input():
#Get the input in form of strings and convert into list
print("Enter the board here: ")
lines = []
while True:
line = input()
if line:
lines.append(line)
else:
break
final = [(list(i)) for i in lines]
return final
def row_check(board):
# row check function which will be used in other two functions as well
text = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
x = True
for row in board:
if sorted(row) == text:
x = True
else:
x = False
return x
def col_check(board):
# Getting the list of 9 lists containing column elements
i = 0
j = 0
cols = [[], [], [], [], [], [], [], [], []]
for j in range(0, 9):
for i in range(0, 9):
cols[j].append(board[i][j])
return (row_check(cols))
def tile_check(board):
#Getting the list of 9 lists converting each tile of 3x3 into 9 element list
lst =[[],[],[],[],[],[],[],[],[]]
i = 0
j = 0
k = 0
while k<9:
for r in range(i,i+3):
for c in range(j, j+3):
lst[k].append(board[r][c])
j = j +3
k = k +1
if j == 9:
j = 0
i = i+3
return (row_check(lst))
#main program
c = get_input()
if row_check(c) and col_check(c) and tile_check(c):
print("YES!")
else:
print("NOPE!!")