【问题标题】:question where you have to check a list of strings and every item has to be longer than the previous item您必须检查字符串列表并且每个项目都必须比前一个项目长的问题
【发布时间】:2020-02-20 02:48:48
【问题描述】:
完成一个函数的函数设计,该函数接受一个字符串列表并确定列表中的每个字符串是否都大于它之前的字符串。假设一个空列表和一个只有一个元素的列表都满足条件(因为没有字符串后跟更长的字符串)。
这是我目前的解决方案。我已经尝试使用嵌套的 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
【问题讨论】:
标签:
python
list
while-loop
counter
accumulate
【解决方案1】:
您可以检查基于字符串长度的排序列表是否与您传入的相同
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)
【解决方案2】:
在不大幅修改您的工作的情况下,您可以在您的 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