I am trying to solve a contest question: https://dmoj.ca/problem/ccc18s2. Basically you're given an input where the first line gives you the number of lines the input is, then you're given a series of integers(max: 10^9). Sample Input:
3
4 3 1
6 5 2
9 7 3
Then the program has to rotate this grid until the first element of every column is less than the second element in every column and so on. Each row must also be in ascending order.
Sample Output:
1 2 3
3 5 7
4 6 9
import sys
n = int(sys.stdin.readline())
row=[]
appendtorow = row.append
for i in range(0,n):
inputx = (sys.stdin.readline()).rstrip()
inp = inputx.split(" ")
appendtorow(inp)
def rotate(row):
new =[]
for i in range(0,n):
temp=[]
for j in range(0,n):
temp.append(row[n-1-j][i])
new.append(temp)
return new
def printout():
for i in range(0,n):
for j in range(0,n):
x=row[i]
y=x[j]
sys.stdout.write(y)
sys.stdout.write(" ")
sys.stdout.write("\n")
def check(row):
m=False
g=False
f=False
for i in range(0,n):
for j in range(0,n-1):
if(row[n-1][i]>row[n-1-j][i]):
m=True
for i in range(0,n):
for j in range(0,n-1):
if(row[i][0]<row[i][j+1]):
g=True
if(g==True and m==True):
f=True
return f
flag=0
while(flag==0):
g=check(row)
if(g==True):
printout()
flag=1
else:
row = rotate(row)
I tried to increase it's speed with stdin, stdout and moving append out of loops as suggested by this guide: https://wiki.python.org/moin/PythonSpeed/PerformanceTips. But the program takes twice the time(2s) of the time limit(1s) and these don't seem to help.
How can I optimize this? Does calling functions increase the time a program takes to execute?