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

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

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 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()

Convert string to integers

I'm just starting out with programming, and I know I'm still missing some of the basics, but I'm trying to work this out. I have a list of 3 and 4 digit numbers that I've brought in from a text file, and I'm trying to get a sum of these numbers. So far all I can get python to do is perform a sum of each individual number, so if the first number in the list is 427, it's printing 13, rather than adding 427 + 504 + 219, etc.
This is what I have:
myList = []
inFile = open('E:/GIS/GTECH 731/NYCElementarySchools.txt', 'r')
for row in inFile:
col = row.split('\t')
if col[1]=='BK':
myList = (col[3])
intList = [int(x) for x in myList]
print sum(intList)
Additionally, when i have it print length, it gives me a list of 3's and 4's, telling me the length of each number, not giving me the total count of numbers.
I must be missing something fundamental, but I don't know what it is! Any suggestions are appreciated! Thanks!
This:
myList = (col[3])
will set myList to a str, not a list, which would be a representation of a number. Thus:
intList = [int(x) for x in myList]
would convert the digits to numbers. You want int(myList) to convert the whole string to a number.
You can keep a running total (initialised to 0) and do total += int(myList) to total all of the numbers. Then after the loop you can print the result.
In your code:
col = row.split('\t')
if col[1]=='BK':
myList = (col[3])
intList = [int(x) for x in myList]
print sum(intList)
'col = row.split('\t')' makes a list which is divided by TAB.
If the line which is read from the file, looks like this:
# \t is TAB
SOMETHING\tBK\t1\t2\t3
The col structure is:
col[0] = SOMETHING
col[1] = BK
col[2] = 1
col[3] = 2
col[4] = 3
So, if you intend sum col[3] to col[...] then use col[3:] = list of col[3], col[4]
Thus, if you want to accumulate sum result you need another variable.
myList = []
inFile = open('E:/GIS/GTECH 731/NYCElementarySchools.txt', 'r')
sumList = []
for row in inFile:
row_total = 0
col = row.split('\t')
if col[1]=='BK':
intList = [int(x) for x in col[3:]]
row_sum = sum(intList)
# row_sum = map(lambda x: int(x), col[3:])
print 'row total: %d' % (row_sum)
sumList.append(row_sum)
print 'total: %d' % (sum(sumList))
Probably you want to use a slice to assign myList
myList = col[3:]
this will return a list everything from the 3rd column on.

Python sudoku checker

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!!")

Categories

Resources