Matrix Rotation in Python - python

In this Program I need to rotate the matrix by one element in clockwise direction.I had done with the code but I have a problem with removing the newlione in the the last row in the given Matrix. In this Program the user has to give the input. The code is
def rotate(m):
if not len(m):
return
top=0
bottom=len(m)-1
left=0
right=len(m[0])-1
while(left<right and top < bottom):
prev=m[top+1][left]
for i in range(left,right+1):
curr=m[top][i]
m[top][i]=prev
prev=curr
top+=1
for i in range(top,bottom+1):
curr=m[i][right]
m[i][right]=prev
prev=curr
right-=1
for i in range(right,left-1,-1):
curr=m[bottom][i]
m[bottom][i]=prev
prev=curr
bottom-=1
for i in range(bottom,top-1,-1):
curr=m[i][left]
m[i][left]=prev
prev=curr
left+=1
return m
def printMatrix(m):
for row in m:
print(' '.join(str(n) for n in row))
n = int(input())
m = []
for i in range(1,n+1):
l = list(map(int, input ().split ()))
m.append(l)
marix=rotate(m)
printMatrix(m)
The Test Case is given Below
Input
4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Expected Output:
5 1 2 3\n
9 10 6 4\n
13 11 7 8\n
14 15 16 12
Actual Output Which i get:
5 1 2 3\n
9 10 6 4\n
13 11 7 8\n
14 15 16 12\n

This is just an issue with your printMatrix() function, print() by defaults adds a newline. You could replace it with below to eliminate the last newline (though I'm not sure why this is so critical):
def printMatrix(m):
print('\n'.join(' '.join(str(n) for n in row) for row in m), end='')

Related

I cant get my code to draw a number pattern with nested loops in Python that will align all number printouts in a neat manner

Use nested for loops to create the following printout:
The number of rows should be read from the user. Use formatted printouts
so that the numbers are aligned even for two-digit numbers.
• All printed numbers correspond to column numbers.
• No number is printed if the column number is less than the row number.
• Print a suitable number of spaces to fill an empty column.
# Program to print a pattern with numbers
print("Program to print a pattern with numbers ")
print("-" * 50)
n = int(input("Please enter the number of rows "))
print("-" * 50)
for i in range(n + 1):
# Increase triangle hidden
for j in range(i):
print(" ", end=' ')
# Decrease triangle to include numbers in pattern not in increment
for j in range(i, n):
print(j + 1, end=" ")
print()
The code above produces the required output but the numbers are not aligned in an input with 2 digits. How do I format the iterables to make a perfectly aligned output printout.
Output:
This is how you might modify your code to use str.rjust. Adjust the 2 in rjust(2) to whatever number you want.
print("Program to print a pattern with numbers ")
print("-" * 50)
n = int(input("Please enter the number of rows "))
print("-" * 50)
for i in range(n + 1):
# Increase triangle hidden
for j in range(i):
print(" ".rjust(2), end=" ")
# Decrease triangle to include numbers in pattern not in increment
for j in range(i, n):
print(str(j+1).rjust(2), end=" ")
print()
For your example, this gives:
Program to print a pattern with numbers
--------------------------------------------------
Please enter the number of rows 12
--------------------------------------------------
1 2 3 4 5 6 7 8 9 10 11 12
2 3 4 5 6 7 8 9 10 11 12
3 4 5 6 7 8 9 10 11 12
4 5 6 7 8 9 10 11 12
5 6 7 8 9 10 11 12
6 7 8 9 10 11 12
7 8 9 10 11 12
8 9 10 11 12
9 10 11 12
10 11 12
11 12
12
You can use str.rjust to right-justify a string. As long as you know the overall length of each line, that makes it easy to align each line so that they're all aligned on the right:
>>> n = 5
>>> for i in range(1, n+1):
... print(''.join(str(j).rjust(3) for j in range(i, n+1)).rjust(n*3))
...
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5

how can I decrease execution time needed for python code?

#https://www.codechef.com/problems/GRIDGM
from sys import setrecursionlimit
setrecursionlimit(10**6)
def sol(l,lst):
sum=0
for i in range(l[0],l[2]+1):
for j in range(l[1],l[3]+1):
#print(lst[i-1][j-1],end="")
sum += lst[i-1][j-1]
#print('---')
#print("sol below")
return sum
for _ in range(int(input())):
n,m=map(int, input("enter values of n and m").split())
lst=[]
for _ in range(n):
lst.append(list(map(int,input("enter a row").split())))
#print(lst)
#q=int(input())
#dj=[] #it saves x y and a b
for _ in range(int(input("enter no of queries"))):
#v=list(map(int,input().split()))
#print(v)
#print('sol below')
print(sol(list(map(int,input("enter cordinates").split())),lst))
sample input
1
4 4
9 13 5 2
1 11 7 6
3 7 4 1
6 0 7 10
2
2 1 4 2
2 2 4 4
output
28
53
above code took 5.1 sec to execute.
in this question, I have to find sum of elements within given coordinates a,b and x,y
more information about this problem can be found in the link below.
https://www.codechef.com/problems/GRIDGM

Write a program to prompt for square height h and print the even numbers in a square shape?

I'm not sure how to do this. I know how to print a square shape by prompting for row and col, but don't quite understand how to only prompt for height and print an array of even numbers.
col = eval(input("Enter the number of columns: "))
row = eval(input("Enter the number of rows: "))
for j in range(row):
for i in range(col):
print("*", end=" ")
print()
this is how I would set up printing a square of asterisks, but how would I do this while only prompting for height and printing out even numbers? For example, if my height is "3", it should print out an array that looks like this:
0 2 4
6 8 10
12 14 16
Using next() on an iterator of the numbers:
h = 3
ns = iter(range(0,h**2*2,2))
for r in range(h):
for c in range(h):
print(next(ns), end='\t')
print()
which gives:
0 2 4
6 8 10
12 14 16
Using slicing and str.join:
h = 4
ns = list(range(0,h**2*2,2))
for r in range(0,len(ns),h):
print(" ".join(str(c) + "\t" for c in ns[r:r+h]))
which gives:
0 2 4 6
8 10 12 14
16 18 20 22
24 26 28 30
Here is an approach by making a nested list and printing it out using a formatting function. Can replace the list comprehension with a generator comprehension for large lists.
def print_even_matrix(h):
l = [[2*(i + j) for j in range(h)] for i in range(0, h**2, h)]
listtab = lambda x: '\t'.join(map(str, x))
print '\n'.join(map(listtab, l))
>>> print_even_matrix(3)
0 2 4
6 8 10
12 14 16
>>> print_even_matrix(4)
0 2 4 6
8 10 12 14
16 18 20 22
24 26 28 30

Print a number table in a simple format

I am stuck trying to print out a table in Python which would look like this (first number stands for amount of numbers, second for amount of columns):
>>> print_table(13,4)
0 1 2 3
4 5 6 7
8 9 10 11
12 13
Does anyone know a way to achieve this?
This is slightly more difficult than it sounds initially.
def numbers(n, r):
print('\n'.join(' '.join(map(str, range(r*i, min(r*(i + 1), n + 1)))) for i in range(n//r + 1)))
numbers(13, 4)
#>>> 0 1 2 3
4 5 6 7
8 9 10 11
12 13
def numbers(a,b):
i=0;
c=0;
while i<=a:
print(i,end="") #prevents printing a new line
c+=1
if c>=b:
print("\n") #prints a new line when the number of columns is reached and then reset the current column number
c=0;
I think it should work
def num2(n=10, r=3):
print('\n'.join(' '.join(tuple(map(str, range(n+1)))[i:i+r]) for i in range(0, n+1, r)))
<<<
0 1 2
3 4 5
6 7 8
9 10

Number Pyramid Nested for Loop

I'm wondering if you could help me out. I'm trying to write a nested for loop in Python 3 that displays a number pyramid that looks like;
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
Can anybody help me out? It would be much appreciated!
This is what I have so far:
col = 1
for i in range(-1, 18, col*2):
for j in range(1, 0, 1):
print(" ", end = "")
for j in range(i, 0, -2):
print(j, end = " ")
print()
So, I can only get half of the pyramid to display.
I guess the main problems I'm having is:
How do i get the output to display an increasing and then decreasing value (ie. 1, 2, 4, 2, 1)?
An alternate way using list comprehensions.
Always break the problem down into digestable chunks. Each line is a mirror of itself, so lets just deal with first making out set of numbers we need.
This generates a list of strings that hold all powers of two which is what this is generating
lines = []
for i in range(1,9):
lines.append([str(2**j) for j in range(i)])
But if we just print this list, a) its going to only have half, and b) its going to mush the numbers together. We need to buffer the numbers with spaces. Fortunately, the last row will have the largest digits for any column, so:
Firstly, how long does each line need to end up being (we need this later) and also, what is the longest number in each column. We can use len as we cast the numbers to strings above.
b = len(lines[-1])
buffers = [len(x) for x in lines[-1]]
Now I have everything I need to print the strings (we stopped using numbers above):
So, for each line, find out how long it is, and expand the array it to the length of the longest line by filling the left of the array with empty strings (for this we're still pretending we're only printing the left half of the triangle):
for line in lines:
l = len(line)
line = [" "]*(b-len(line)) + line
With each line now buffered, we'll make a new array that we will print from. By zip()ing together the line and the buffer, we can easily right justify (String.rjust()) numberic strings, expanded out to the length required.
out = []
for x,y in zip(line,buffers):
out.append(x.rjust(y))
Remmeber until now, we've still just been working with the left half of the pyramid. So we take the output array, reverse it (array[::-1]) and then take every element but the first (array[1:]) and join it all together with a string and print it out.
print(" ".join(out+out[::-1][1:]))
Voila! The completed code:
lines = []
for i in range(1,9):
lines.append([str(2**j) for j in range(i)])
b = len(lines[-1])
buffers = [len(x) for x in lines[-1]]
for line in lines:
l = len(line)
line = [" "]*(b-len(line)) + line
out = []
for x,y in zip(line,buffers):
out.append(x.rjust(y))
print(" ".join(out+out[::-1][1:]))
Output:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
height = 8
maxHeight = height - 1
for i in range(height):
k, Max = 1, i * 2 + 1
print(maxHeight * " ", end="")
maxHeight -= 1
for j in range(Max):
print("%5d" % k, end="")
if (j < (Max // 2)):
k *= 2
else:
k //= 2
print()
Output:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
This could be the other 9 line solution.
Generate power of two's numbers as series
Find the offset need to add in each rows
Print the empty space for the each row before printing the palindromic list.
Ie. (offset * (n - i)) times " "(empty space)
Build palindromic series by slice operation ie. temp + temp[::-1][1:]
Print the palindromic series and offset spaces relative to the length of the number you are printing.
Code:
n = 8
numbers = [2**x for x in range(n)] # Generate interseted series.
offset = len(str(numbers[-1:])) -1 # Find the max offset for the tree.
for i in range(1, n+1): # Iterate n times. 1 to n+1 helps eazy slicing.
temp = numbers[:i] # Slice series to get first row numbers.
print(' ' * (offset * (n - i)), end=" ") # Prefix spaces, multiples of offset.
for num in temp + temp[::-1][1:]: # Generate palindromic series for the row.
print(num, end=" " * (offset - len(str(num)))) # Adjust offset for the number.
print('')
output:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1

Categories

Resources