此代码的目的是按字母顺序查找最先出现的最长字符串并返回该子集。在
我可以执行一次代码,但当我尝试循环它时,我得到'NoneType'对象不可读取(指向最后一行)。我已经确定我返回的和输入的都不是非类型的,所以我觉得我缺少了一个基本的。在
这是我在班上的第一个项目,所以代码不需要是“最好的”或最有效的方法-它只是在这一点上学习基础知识。在
s = 'efghiabcdefg'
best = ''
comp = ''
temp = ''
def prog(comp, temp, best, s):
for char in s:
if comp <= char: #Begins COMParison of first CHARacter to <null>
comp = char #If the following character is larger (alphabetical), stores that as the next value to compare to.
temp = temp + comp #Creates a TEMPorary string of characters in alpha order.
if len(temp) > len(best): #Accepts first string as longest string, then compares subsequent strings to the "best" length string, replacing if longer.
best = temp
if len(best) == len(s): #This is the code that was added...
return(s, best) #...to fix the problem.
else:
s = s.lstrip(temp) #Removes those characters considered in this pass
return (str(s), str(best)) #Provides new input for subsequent passes
while len(s) != 0:
(s, best) = prog(comp, temp, best, s)
不是所有情况下都是这样。在Python中,如果函数结束时没有显式的
return
语句,它将返回None
。在例如,如果输入字符串为空,请考虑返回一些内容。在
prog
正在返回None
。当您试图将结果解压到元组(s,best)时,会出现错误您需要修复您的逻辑,以保证}。如果您的代码从未在循环中执行
prog
不会返回{else
子句,它将返回None
。在相关问题 更多 >
编程相关推荐