猿问

为什么函数不使用默认值?

我试图使用递归函数编写字符串匹配程序。该函数首先创建一个名为 tuple1 的空列表来添加点。然后它返回列表。但是,当我尝试两次使用此函数时,该函数会将点添加到在上一个函数中创建的列表。为什么函数在第二次调用中不使用默认值 tuple1 = []?任何想法??


程序输出:


[0, 3, 5, 9, 11, 12, 15, 19]


[0, 3, 5, 9, 11, 12, 15, 19, 0, 5, 15]


顺便说一句,这是麻省理工学院共享的开放课件的作业。


def subStringMatchExact(target, key, counter=0, tuple1=[]):

    if len(target) < len(key):

       return tuple1


    else:

       counter += 1


       if target[:len(key)] == key:

          tuple1.append(counter-1)

       return subStringMatchExact(target[1:], key, counter, tuple1)


print(subStringMatchExact("atgacatgcacaagtatgcat", "a"))

print(subStringMatchExact("atgacatgcacaagtatgcat", "atg"))


绝地无双
浏览 115回答 3
3回答

慕田峪4524236

解决方法是:def foo(x=None):&nbsp; &nbsp; if x is None:&nbsp; &nbsp; &nbsp; &nbsp; x = []&nbsp; &nbsp; # do stuff您可以在此处阅读更多内容 http://effbot.org/zone/default-values.htm

白衣染霜花

由于默认值是对默认值的引用,因此并非每次都创建默认值。因此,如果您运行这样的示例:def f(x=[]):&nbsp; &nbsp; x.append(1)&nbsp; &nbsp; return xprint(f()) #prints [1]print(f()) #prints [1,1]解决方法是使用不可变的元组并将其转换为列表:def f(x=()):&nbsp; &nbsp; if not isinstance(x, list):&nbsp; &nbsp; &nbsp; &nbsp; input = list(x)&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; input = x&nbsp; &nbsp; input.append(1)&nbsp; &nbsp; return inputprint(f()) #[1]print(f()) #[1]这样它就可以工作了

汪汪一只猫

当您使用可变对象作为默认值时,这里会出现混淆。在这里,tuple1 只是在每次调用函数时添加到列表中。以下是一个解决方法:def subStringMatchExact(target, key, counter=0, tuple1=None):&nbsp; &nbsp; if tuple1 == None:&nbsp; &nbsp; &nbsp; &nbsp; tuple1 = []&nbsp; &nbsp; if len(target) < len(key):&nbsp; &nbsp; &nbsp; &nbsp;return tuple1&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp;counter += 1&nbsp; &nbsp; &nbsp; &nbsp;if target[:len(key)] == key:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tuple1.append(counter-1)&nbsp; &nbsp; &nbsp; &nbsp;return subStringMatchExact(target[1:], key, counter, tuple1)
随时随地看视频慕课网APP

相关分类

Python
我要回答