I have an N x N matrix
filled with 0's as follows:
str1 = "Patrick"
str2 = "Garrick"
matrix = [[0 for _ in range(len(str1))] for _ in range(len(str2))]
I am iterating over the first column of the matrix, and if a certain condition is met, I would like to fill in the rest of the first column with 1's, how can I do this? Here is my code so far:
for i in range(len(str2)):
if str2[i] == str1[0]: #this is the condition!
matrix[i:][0] = 1
break
else:
matrix[i][0] = 0
But the above gives me an error, since we cannot do matrix[i:][0] = 1
, and I do understand why, but how else can I achieve the above?
CodePudding user response:
The pure python answer is that you need to iterate:
flag = 0
for i in range(len(str2)):
if str2[i] == str1[0]:
flag = 1
matrix[i][0] = flag
You can make it simpler by finding the index up front since your matrix is already zeros:
try:
i = str2.find(str1[9])
except:
pass
else:
for j in range(i, len(str2)):
matrix[j][0] = 1
You can cheat for the first column (won't work for the rest):
try:
i = str2.find(str1[9])
except:
pass
else:
matrix[i:] = [1] [0 for _ in range(len(str1) - 1)]
If you're willing to use numpy, you can do this without looping explicitly, delegating instead to under-the-hood vectorized loops:
s1 = np.array(list(str1))
s2 = np.array(list(str2))
matrix = np.maximum.accumulate(s2[:, None] == s1, axis=0)
CodePudding user response:
I think this does what you want. Note I'm using different strings as input so the conditional will be be met (several times).
from pprint import pprint
str1 = "Patrick"
str2 = "GaPPicP"
matrix = [[0 for _ in range(len(str1))] for _ in range(len(str2))]
for i in range(len(str2)):
if str2[i] == str1[0]: # this is the condition!
for j in range(len(str2)):
matrix[j][i] = 1
pprint(matrix)
Output:
[[0, 0, 1, 1, 0, 0, 1],
[0, 0, 1, 1, 0, 0, 1],
[0, 0, 1, 1, 0, 0, 1],
[0, 0, 1, 1, 0, 0, 1],
[0, 0, 1, 1, 0, 0, 1],
[0, 0, 1, 1, 0, 0, 1],
[0, 0, 1, 1, 0, 0, 1]]
CodePudding user response:
You just need to loop through range(i, len(str2))
and assign 1
to matrix[j][0]
.
Demo:
str1 = "Patrick"
str2 = "Garrick"
matrix = [[0 for _ in range(len(str1))] for _ in range(len(str2))]
print(matrix)
for i in range(len(str2)):
if str2[i] == str1[0]: # this is the condition!
for j in range(i, len(str2)):
matrix[j][0] = 1
break
else:
matrix[i][0] = 0
print(matrix)
Note: For the given strings, your condition will never become True
. You can test it some other values e.g. with str1 = "aatrick"
.