user2832964
user2832964

Reputation: 125

Python issue with program involving recursion

For a course I am making a program that must involve recursion. This is what I have so far:

def words(letters, start, word):
    while (start) < (len(letters)):
        word = word + letters[start]
        print(word)
        letters = letters.replace(letters[start], "")
        start = (words(letters, start, word))
        return (start + 1)

The goal of the program is to accept a list of letters and output all possible combinations of those letters. I am not sure if the program will work, but before that, I am running into another issue. When I run this with a basic command, e.g.

words("abcd", 0, "")

(the 0 and the "" are just for starting off the command as they are necessary in the future). But when I run that, it outputs, a ab abc abcd, but then stops with an error citing the line return(start + 1) saying the start is not an integer, but a None type. When did start become a None type? And how can I keep it as an integer?

Upvotes: 0

Views: 85

Answers (2)

inspectorG4dget
inspectorG4dget

Reputation: 114035

When you return, you return an int. However, you only do so within your while loop, i.e. when start < len(letters). If that condition is not met, your function returns nothing, i.e. NoneType.
This is why eventually, in your while loop, start becomes a NoneType, which leads to your error.

You could do something like this:

def words(letters, soFar=''):
  if not letters:
    print(soFar)
  else:
    for i,char in enumerate(letters):
      words(letters[:i]+letters[i+1:], soFar+char)

Upvotes: 2

qwertynl
qwertynl

Reputation: 3933

Remember to return something if the while loop doesn't get entereed (which is basically an if statement in your example):

def words(letters, start=0, word=""):
    if start < len(letters):
        word = word + letters[start]
        print(word)
        letters = letters.replace(letters[start], "")
        start = words(letters, start, word)
        return start + 1
    else:
        return 0

Also I set some default values, so you can now do this:

words(letters="abcd")

Upvotes: 2

Related Questions