Welcome to LeetCode Discuss.  Please read the FAQ to help yourself making the best use of Discuss.
Ask a Question
Back to Problem

Welcome to LeetCode Discuss.

This is a place to ask questions related to only OJ problems.

Please read the FAQ to help yourself making the best use of Discuss.

Python code gets Compile Error with "import collections"

0 votes
19 views

Why does the below code get Compile Error? It works on my laptop. p.s: The Java solution is Accepted (Nothing's wrong with algorithm).

import collections

class Solution:
    def ladderLength(self, start, end, words):
        words.append(start)
        words.append(end)
        n = len(start)
        d = {}

        for w in words:
            d[w] = 0;
        d[start] = 1;

        q = collections.deque()
        q.append(start)

        while len(q) > 0:
            s = q.popleft()
            chars = list(s)
            for i in range(n):
                head = ''.join(chars[0:i])
                tail = ''.join(chars[i + 1:n])

                for j in range(ord('a'), ord('z')):
                     t = head + chr(j) + tail
                     if t in d and d[t] == 0:
                        d[t] = d[s] + 1
                        q.append(t)
                        if t == end: return d[t]

        return 0
asked Feb 19 in Word Ladder by MinhMinh (140 points)

1 Answer

0 votes

Remove your import statement and it should compile fine. The collections module is imported automatically for you.

answered Feb 19 by 1337c0d3r (10,420 points)

...