0

I am trying to learn python and am doing leetcode problems to become more familiar with the syntax. I am getting the error:

NameError: name 'dfs' is not defined
    dfs(result, temp, 0, n, k)

I am also not sure if I am declaring the lists correctly or if I should pass self as a parameter to the functions.

class Solution:
    def dfs(self, result: List[List[int]], temp:List[int], index: int, n: int, k: int):
        for i in range(index + 1, n + 1):
            temp.push(i)
            if len(temp) == k:
                result.push(temp)
                temp.pop()
                return 
            else:
                dfs(result, temp, i, n, k)
                temp.pop()
                
    def combine(self, n: int, k: int) -> List[List[int]]:
        result = [[]];
        temp = [];
        dfs(result, temp, 0, n, k)
        return result
1
  • 1
    Your syntax is fine, it's how you're referring to the functions that's the problem. BTW get rid of the semicolons; they do nothing. Commented Aug 10, 2020 at 18:32

4 Answers 4

2

It should be self.dfs(result, temp, 0, n, k). So change to self.dfs wherever you are using dfs

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

Comments

2

In this example, dfs is a method on Solution, so when using it from other methods on Solution you want to call self.dfs instead of dfs. Alternatively, you could move the definition of dfs outside of the class, like so:

def dfs(...):
   ...

class Solution:
   ...

I assume that the reason these are methods on a class is something about the format of leetcode's interface that requires the use of classes rather than free-standing functions, but probably it would be more idiomatic in Python for dfs to be a free-standing function rather than a method in most cases. Generally if something doesn't need to use the self argument and doesn't need to be called by something that only has a reference to a specific object, there's no need to make it a method.

1 Comment

Yeah this seems to be a quirk of Leetcode. It might be more idiomatic to make dfs a staticmethod, but yeah ideally it would be a free-standing function.
1

It's not the best idea to use itertools.combinations for solving these algorithm problems, but just in case you didn't know, here we can solve the problem with that.

This'll pass:

class Solution:
    def combine(self, n, k):
        return tuple(itertools.combinations(range(1, n + 1), k))

Here are some of LeetCode's solutions with comments, implementing the same idea:

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        # init first combination
        nums = list(range(1, k + 1)) + [n + 1]
        
        output, j = [], 0
        while j < k:
            # add current combination
            output.append(nums[:k])
            # increase first nums[j] by one
            # if nums[j] + 1 != nums[j + 1]
            j = 0
            while j < k and nums[j + 1] == nums[j] + 1:
                nums[j] = j + 1
                j += 1
            nums[j] += 1
            
        return output

With backtracking:

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        def backtrack(first = 1, curr = []):
            # if the combination is done
            if len(curr) == k:  
                output.append(curr[:])
            for i in range(first, n + 1):
                # add i into the current combination
                curr.append(i)
                # use next integers to complete the combination
                backtrack(i + 1, curr)
                # backtrack
                curr.pop()
        
        output = []
        backtrack()
        return output

References

  • For additional details, please see the Discussion Board which you can find plenty of well-explained accepted solutions in there, with a variety of languages including efficient algorithms and asymptotic time/space complexity analysis1, 2.

Comments

1

If you declare the functions inside the Solution class, then you have to refer to them as self.dfs(...) only if you don't want to do that, then write your function outside the Solution class. Something like this:

def dfs(...):
    # your body

class Solution(..):
    def combine(...):

And also, in Python, it is not 'push' for lists it is 'append' so please replace temp.push to temp.append

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.