问题在哪里你必须检查字符串列表并且每个项目都必须比前一个项目长
question where you have to check a list of strings and every item has to be longer than the previous item
完成一个函数的函数设计,该函数接受一个字符串列表并确定列表中的每个字符串是否都大于它前面的字符串。假设一个空列表和一个只有一个元素的列表都满足条件(因为没有字符串后跟更长的字符串)。
这是我目前的解决方案。我用嵌套的 for 循环尝试过,但似乎没有用。我只是不知道如何在不超出范围的情况下将列表中的两项与紧挨着的一项进行比较
def growing_strings(los):
sum=0
counter= 0
while len(los[counter]) < len(los[counter+1]):
sum+=1
counter+=1
if sum==len(los):
return True
else:
return False
你可以只检查根据字符串长度排序的列表是否与你传入的相同
def growing_strings(los):
return sorted(los, key=lambda x: len(x)) == los
如果不允许相同长度的字符串,添加额外的检查
return sorted(los, key=lambda x: len(x)) == los and len({len(x) for x in los}) == len(los)
在不大幅修改您的工作的情况下,您可以在 while 循环中包含一个检查 counter+1
是否小于列表的长度:
def growing_strings(los):
sum=0
counter= 0
while counter+1 < len(los) and len(los[counter]) < len(los[counter+1]):
sum+=1
counter+=1
if sum==len(los):
return True
else:
return False