[英]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, eg
当我使用基本命令运行此命令时,例如
words("abcd", 0, "")
(the 0
and the ""
are just for starting off the command as they are necessary in the future). (
0
和""
仅用于启动命令,因为将来需要使用它们)。 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
. 但是当我运行该命令时,它输出ab abc abcd,但随后由于错误而停止,引用行return(start + 1)表示
start
不是整数,而是None type
。 When did start become a None type
? 什么时候开始成为
None type
? And how can I keep it as an integer? 以及如何将其保持为整数?
Remember to return something if the while loop doesn't get entereed (which is basically an if statement in your example): 如果while循环没有被输入,请记住要返回一些内容(在您的示例中,这基本上是一个if语句):
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")
When you return
, you return an int
. return
,将返回一个int
。 However, you only do so within your while loop, ie when start < len(letters)
. 但是,仅在while循环内(即,当
start < len(letters)
才这样做。 If that condition is not met, your function returns nothing, ie NoneType
. 如果不满足该条件,则您的函数将不返回任何内容,即
NoneType
。
This is why eventually, in your while loop, start
becomes a NoneType
, which leads to your error. 这就是为什么最终在您的while循环中,
start
变为NoneType
,从而导致您的错误的原因。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.