Answer the question
In order to leave comments, you need to log in
How to find an error in a Python program (problem solution)?
problem :
Write a program that takes as input a rectangular matrix as a sequence of rows ending with a row containing only the string "end" (without quotes)
The program should output a matrix of the same size, in which each element in position i, j is equal to the sum of the elements of the first matrices at positions (i-1, j), (i+1, j), (i, j-1), (i, j+1). For extreme characters, the adjacent element is on the opposite side of the matrix.
In the case of a single row/column, the element is itself a neighbor in the corresponding direction.
Sample Input 1:
9 5 3
0 7 -1
-5 2 9
end
Sample Output 1:
3 21 22
10 6 19
20 16 -1
Sample Input 2:
1
end
Sample Output 2:
4
Memory Limit: 256 MB
Time Limit: 5 seconds
my solution is:
a=''
b=[]
q=0
num=-1
while a!="end":
a=input()
for i in a.replace(' ',''):
if i=='-':
q+=1
continue
elif i=='e' or i=='n' or i=='d':
continue
else:
if q==1:
b.append(int(i)-int(i)*2)
q=0
else:
b.append(int(i))
num+=1
gor=num
vert=len(b)//gor
c=[[0 for k in range(vert)] for n in range(gor)]
h=0
for i in range(gor):
for j in range(vert):
c[i][j]=int(b[h])
h+=1
z=[[0 for k in range(vert)] for n in range(gor)]
for i in range(len(z)):
for j in range(len(z[0])):
if j==len(z[0])-1 and i!=len(z)-1:
z[i][j]=int(c[i-1][j])+int(c[i+1][j])+int(c[i][j-1])+int(c[i][0])
elif j!=len(z[0])-1 and i==len(z)-1:
z[i][j]=int(c[i-1][j])+int(c[0][j])+int(c[i][j-1])+int(c[i][j+1])
elif j==len(z[0])-1 and i==len(z)-1:
z[i][j]=int(c[i-1][j])+int(c[0][j])+int(c[i][j-1])+int(c[i][0])
else:
z[i][j]=int(c[i-1][j])+int(c[i+1][j])+int(c[i][j-1])+int(c[i][j+1])
s=0
for i in range(len(z)):
for j in z[int(i)]:
print(str(j)+' ',end='')
s+=1
if s==vert:
print('')
s=0
Answer the question
In order to leave comments, you need to log in
You think that all numbers are numbers. That is, that all elements of the matrix modulo from 0 to 9. But this is obviously not the case. To make it easier to get parts from a string, use the split method :str_numbers = a.split()
Perhaps you are not within the limits. memory and time. Is there a description of the sixth test?
I didn’t delve into the code, because for a long time, but I can advise you to look for a solution with fewer cycles.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question