0

The output for G and G1 list is different.

numCourses = 2
prerequisites = [[1,0]]

G = [[] for i in range(numCourses)]

G1 = [[]]*numCourses

for i,j in prerequisites:
    G[j].append(i)

for i,j in prerequisites:
    G1[j].append(i)

I get following output G = [[1],[]] and G1 = [[1],[1]]

1

1 Answer 1

1

It's a classic python gotcha

G = [[] for i in range(numCourses)]

creates numCourses new, empty list, while

G1 = [[]]*numCourses

first creates the (inner) empty list, and then a list consisting of numCourses copies of it. That's why when you change one list in G1 all of them change.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.