How Can I Fill The Remainder Of The First Column Of An N X N Matrix With 1's, Once A Certain Condition Is Met In My For Loop?
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 fi
Solution 1:
The pure python answer is that you need to iterate:
flag = 0for 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:
passelse:
for j inrange(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:
passelse:
matrix[i:] = [1] + [0for _ inrange(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)
Solution 2:
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 = [[0for _ inrange(len(str1))] for _ inrange(len(str2))]
for i inrange(len(str2)):
if str2[i] == str1[0]: # this is the condition!for j inrange(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]]
Solution 3:
You just need to loop through range(i, len(str2))
and assign 1
to matrix[j][0]
.
Demo:
str1 = "Patrick"
str2 = "Garrick"
matrix = [[0for _ inrange(len(str1))] for _ inrange(len(str2))]
print(matrix)
for i inrange(len(str2)):
if str2[i] == str1[0]: # this is the condition!for j inrange(i, len(str2)):
matrix[j][0] = 1breakelse:
matrix[i][0] = 0print(matrix)
Note: For the given strings, your condition will never become True
. You can test it some other values e.g. with str1 = "aatrick"
.
Post a Comment for "How Can I Fill The Remainder Of The First Column Of An N X N Matrix With 1's, Once A Certain Condition Is Met In My For Loop?"