<p>此代码的目的是按字母顺序查找最先出现的最长字符串并返回该子集。在</p>
<p>我可以执行一次代码,但当我尝试循环它时,我得到'NoneType'对象不可读取(指向最后一行)。我已经确定我返回的和输入的都不是非类型的,所以我觉得我缺少了一个基本的。在</p>
<p>这是我在班上的第一个项目,所以代码不需要是“最好的”或最有效的方法-它只是在这一点上学习基础知识。在</p>
<pre><code>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)
</code></pre>