为什么我的函数返回两个重复的值?
我正在做一个练习问题,我需要在字符串列表中找到最长的公共前缀。
示例:
Input: strs = ["flower","flow","flight"]
Output: "fl"
我的处理方法如下:
def my_function(strs):
### get the length of shortest string in list and assign to "window"
min_len = min([len(x) for x in strs])
window = min_len
### chop all items in list to length of shortest item
for i in range(window):
if window == 0:
return ''
strs = [x[:window] for x in strs]
### Check the length of the set() of all items. If it's longer than 1,
### shorten the window and re-check
if len(set(strs)) == 1:
answer = list(set(strs))
return answer[0]
else:
window += -1
当我使用上面给出的测试用例时,我的函数返回:
fl
fl
为什么我会得到这个重复?
I'm doing a practice problem where I need to find the longest common prefix in a list of strings.
Example:
Input: strs = ["flower","flow","flight"]
Output: "fl"
I'm approaching this as follows:
def my_function(strs):
### get the length of shortest string in list and assign to "window"
min_len = min([len(x) for x in strs])
window = min_len
### chop all items in list to length of shortest item
for i in range(window):
if window == 0:
return ''
strs = [x[:window] for x in strs]
### Check the length of the set() of all items. If it's longer than 1,
### shorten the window and re-check
if len(set(strs)) == 1:
answer = list(set(strs))
return answer[0]
else:
window += -1
When I use the test case given above, my function returns:
fl
fl
Why am I getting this duplication?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在使用一个怪异的循环,其中将“ for”递增“窗口”,但根据条件将其降低。这会导致不一致的迭代。
循环使用
,然后手动修改计数器,或者对
循环使用,并且不要修改计数器。
这说明您的方法不是那么有效,而是在位置后平行地检查字符:
'fl'
You're using a weird loop where you increment "window" with the "for", but decrement it based on a condition. This causes an inconsistent iteration.
Either use a
while
loop and modify the counter manually, or use afor
loop and don't modify the counter.That said your approach of not so efficient, rather check the characters in parallel position after position:
Output:
'fl'
在 @Mozway的帮助下,我能够使用
成功执行该函数,而
语句:With @mozway's help, I was able to successfully execute the function using a
while
statement: