Fill only the elements in the top and bottom row with zeroes - python

I am trying to write a Python statement for performing the following task with a table of m rows and n columns.
I have to fill only the top row and bottom row with zeros.
So far I have:
list = []
for i in range(m):
for j in range(n):
I'm not sure what to do next. How can I access just the first and last row? Thank you!

Code based on your provided information :
list = []
for x in range(0, m):
if x == 0 or x == m:
# your code for filling it with zeros
else:
# your code for "Anything can be in other cells"

You can use:
lst = [[0 if i in (0, m-1) else default_val] * n for i in range(m)]
That roughly does the same as:
lst = [] # do not shadow 'list'
for i in range(m):
lst[i] = []
for j in range(n):
lst[i].append(0 if i in (0, m-1) else default_val)

Related

Transpose of a matrix showing same results as original

I am trying to transpose the matrix but getting the same matrix, this seems to be happening everytime and what is more confusing is that the element of list are swapped but not on this instance.
What is problematic is that I see no change in the end result as the swapping was made for nXn times in the loop.
inp = int(input())
mat = []
for i in range(inp):
submat = list(map(int,input().split(',')))
mat.append(submat)
print(mat)
for i in range(len(mat)):
for j in range(len(mat[0])):
mat[i][j],mat[j][i] = mat[j][i],mat[i][j]
print(mat)
You need to loop in upper triangular matrix only ie from 0,1...len(mat) row wise and row+1, row+2, row+3..len(mat[0]) column wise
# your code goes here
inp = int(input())
mat = []
for i in range(inp):
submat = list(map(int,input().split(',')))
mat.append(submat)
print(mat)
for i in range(len(mat)):
for j in range(i+1, len(mat[0])):
mat[i][j],mat[j][i] = mat[j][i],mat[i][j]
Of course, you are swapping every i, j twice (i, j and later j, i).

Appearing animation for spiral matrix

I'm trying to make a spiral matrix, but when I tried to make the numbers appear one by one, it only shows the lines one by one.
Please help!
import numpy as np
from time import sleep
n = int(input("Width : "))
k = int(input("Space : "))
a = np.zeros((n,n))
print(a/n)
i = 0 #i line
j = 0 #j column
it = -1 #it upper line
id = n #id downer line
jt = -1 #jt left column
jp = n #jp right column
x = k #x starter number
while j < jp:
while j < jp:
a[i][j] = x
x += k
j +=1
it +=1
i=it+1
j=jp-1
while i< id:
a[i][j] = x
x += k
i +=1
jp -=1
j=jp-1
i=id-1
while j > jt:
a[i][j] = x
x += k
j -=1
id -=1
i=id-1
j=jt+1
while i>it:
a[i][j] = x
x += k
i -=1
jt +=1
i=it+1
j=jt+1
for x in a:
print(x)
sleep(0.1)
Here's an example:
Each number is suppose to appear one by one.
(I'm just putting this here so I can post this since I need to add more details)
Not quite trivial.
I found a solution using an empty character array and cursor-manipulation.
This should result in the desired output:
# replace your last "for x in a" loop by the following
def print_array(arr, block_size=4):
"""
prints a 2-D numpy array in a nicer format
"""
for a in arr:
for elem in a:
print(elem.rjust(block_size), end="")
print(end="\n")
# empty matrix which gets filled with rising numbers
matrix_to_be_filled = np.chararray(a.shape, itemsize=3, unicode=True)
for _ in range(a.size):
# find position of minimum
row, col = np.unravel_index(a.argmin(), a.shape)
# add minimum at correct position
matrix_to_be_filled[row, col] = f'{a.min():.0f}'
# write partially filled matrix
print_array(matrix_to_be_filled)
# delete old minimum in a-matrix
a[row, col] = a.max()+1
sleep(0.1)
# bring cursor back up except for last element
if _ < a.size-1:
print('\033[F'*(matrix_to_be_filled.shape[0]+1))
If you are using pycharm, you need to edit the run/debug configuration and active "emulate terminal in output console" to make the special "move up" character work

Sum over some indexes and axis with an irregulat list of list of indices numpy

I want to improve a code where I have to sum over different indices. This is the code:
neighbors = [[1,2,4],[2,0],[1,3],[],[0]]
omega = np.random((5,5,3,3))
#Sum over indices 0 (filtered) and 2
suma = np.zeros((5,3))
for j in range(5):
for l in range(3):
suma[j,l] += np.sum(omega[neighbors[j],j,:,l])
Now I improved a little bit my code using the axis parameter of sum:
suma2 = np.zeros((5,3))
for j in range(5):
suma2[j,:] += np.sum(omega[neighbors[j],j,:,:],axis=(0,1))
I want to know how I can avoid the first loop. I tried creating an array of booleans:
neighbors_bool = np.full((5,5),False,dtype=bool)
for j in range(5):
neighbors_bool[neighbors[j],j] = True
But I don't know how to put it in the sum.

Making Matrices without a library / Inserting nested lists without anything being in a list

I am trying to input and then print a matrix in Python without a library.
Code:
a = []
n = int(input('Length of the row'))
m = int(input('Length of the column'))
for j in range(0, m):
a[j].append([])
for i in range(0, n):
for j in range(0, m):
a[i][j] = int(input())
for i in range(0, n):
print()
for j in range(0, m):
print(a[i][j], end=" ")
Working:
When I put my list to be let's say:
a = [[1,1,1],[1,1,1],[1,1,1]]
And put both m and n to be 3, It works exactly as it should.
Error:
But having only an empty list, as in the code example, I always get an error that list index is out of range.
a[j].append([]) IndexError: list index out of range
Problem:
I don't know how to input nested lists inside a list, and integers inside those nested lists, with a loop, or with anything for that matter.
It is bound to fail:
a = []
# ...
for j in range(0, m):
a[j].append([]) # a is empty, so a[j] must fail!
Try instead:
a = []
n = int(input('Length of the row'))
m = int(input('Length of the column'))
for i in range(m): # m is len of outer list: number of rows == len of column
a.append([])
for j in range(n): # n is len of inner list (those are the rows)
a[i].append(int(input()))
# append as well, as indexes to fill do not exist yet
# the loop could be written as a comprehension:
a = [[int(input()) for _ in range(n)] for _ in range(m)]
for i in range(m):
print()
for j in range(n):
print(a[i][j], end=" ")
Remove the first loop and then make the input loop look something like this:
a = [None] * n
for i in range(n):
a[i] = []
for j in range(m):
a[i].append(int(input()))
append will add elements to a list. a is empty at firsts so a[i] is an error. See my sample that does what you want.
a = []
n = int(input('Enter row count: '))
m = int(input('Enter column count: '))
for i in range(0, n):
a.append([])
for i in range(0, n):
for j in range(0, m):
a[i].append(int(input()))
for i in range(0, n):
print()
for j in range(0, m):
print(a[i][j], end=" ")
print()
Sample run:
Enter row count: 2
Enter column count: 3
1
2
3
4
5
6
1 2 3
4 5 6
When you create a it is empty so you cannot not index anything in it.
>>> a = []
>>> len(a)
0
>>> a[0]
Traceback (most recent call last):
File "<pyshell#126>", line 1, in <module>
a[0]
IndexError: list index out of range
>>>
Just append the empty lists:
>>> a.append([])
>>> a
[[]]
>>> len(a)
1
>>> a[0]
[]
>>>
You have a similar problem when adding to the inner loops. It could be done like this
>>> i = 0
>>> a[i].append(int(input()))
4
>>> a
[[4]]
>>>
You have two mistakes:
You are not being consistent on what are rows and what columns
You are addressing an array/list content that hasn't been allocated any memory
Furthermore, you don't need that third for loop.
n=2
m=3
a=[]
for i in range(0, n):
a.append([])
for j in range(0, m):
a[i].append( int(input()) )
print(a)
which, for input 1-6, gives you
1
2
3
4
5
6
[[1, 2, 3], [4, 5, 6]]

python error - "IndexError: list index out of range"

I'm really new at Python so I apologize in advance if this is a really dumb question. Pretty much, I'm writing a longest common subsequence algorithm with dynamic programming.
Whenever I try to run it, I get the IndexError: list index out of range, and I don't know why because the array I'm adding values to never changes in size. Code snippet for clarity:
def LCS(sequence1, sequence2):
n = len(sequence1)
m = len(sequence2)
D = [[0 for num in range(0,n)]for number in range(0, m)]
for i in range(1, n):
for j in range(1, m):
if(sequence1[i] == sequence2[j]):
D[i][j] = D[i-1][j-1] + 1
else:
D[i][j] = max(D[i-1][j], D[i][j-1])
print D[n][m]
There seem to be two problems:
In the definition of D, you should swap n and m
D = [[0 for num in range(0, m)] for number in range(0, n)]
You have to print (or better: return) the last element of the matrix
return D[n-1][m-1] # or just D[-1][-1]
The issue is with total rows and columns of the matrix(D). Size should be (m+1)*(n+1) and then loop over the matrix. Otherwise you need to return D[m-1][n-1].
def LCS(sequence1, sequence2):
n = len(sequence1)
m = len(sequence2)
D = [[0 for num in range(0,n+1)]for number in range(0, m+1)]
for i in range(1, n+1):
for j in range(1, m+1):
if(sequence1[i-1] == sequence2[j-1]):
D[i][j] = D[i-1][j-1] + 1
else:
D[i][j] = max(D[i-1][j], D[i][j-1])
print D[n][m]
LCS('abcdef' , 'defjkl')

Categories