How can I design a Python function to print a matrix with only the forward diagonal elements set to True?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Popsicle Puzzles
--
Chapters
00:00 Question
01:02 Accepted answer (Score 1)
01:21 Answer 2 (Score 1)
01:40 Thank you
--
Full question
https://stackoverflow.com/questions/6886...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #arrays #multidimensionalarray
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Popsicle Puzzles
--
Chapters
00:00 Question
01:02 Accepted answer (Score 1)
01:21 Answer 2 (Score 1)
01:40 Thank you
--
Full question
https://stackoverflow.com/questions/6886...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #arrays #multidimensionalarray
#avk47
ANSWER 1
Score 1
The problem is that the shorthand you're using to create lists actually just creates copies of the same list. You can check this with the id function:
n = 5
dp = [[False]*n]*n
print([id(x) for x in dp])
ACCEPTED ANSWER
Score 1
The reason is that multiplying with * does not create new object, as @TobyPetty mentioned.
The way to fix would be:
def func(n):
dp = [[[False] for i in range(n)] for x in range(n)]
for i in range(n):
dp[i][i] = True
print(dp)