给定一个字符串和一个非空子字符串子字符串,递归计算最大的子字符串,该子字符串以sub开头和结尾,然后返回它的长度。
sub_sandwich("catcowcat", "cat")→9sub_sandwich("catcowcat", "cow")→3sub_sandwich("cccatcowcatxx", "cat")→9我对我的代码不太满意,我也不知道如何改进它。
def subSandwich(word, char, pos, start, end):
if pos == len(word)-1:
if end == 0:
return len(char)
return end - (start-2)
if word[pos:pos+len(char)] == char:
if start != 0:
end = pos + len(char) - 1
else:
start = pos+1
return subSandwich(word, char, pos + 1, start, end)
def main():
print subSandwich("catcowcat", "cow",0,0,0)
if __name__ == "__main__":
main()发布于 2016-04-09 01:19:33
为了简单起见,只使用2个参数修改子,在1循环时从两端减少1个字符。
#!/usr/bin/python
import unittest
import sys
import os
def subSandwich_new(word, char):
num = word.count(char)
if num ==0:
return 0
elif num ==1:
return len(char)
else:
# first string with length of char
first = word[:len(char)]
match = 0
if first == char:
match = match + 1
else:
# remove 1 char from word
word = word[1:]
# string from end with the length of char
last = word[-len(char):]
if last == char:
match = match + 1
else:
# removing 1 char from word
word = word[:-1]
if match ==2:
# first and last both match
return len(word)
else:
return subSandwich_new(word, char)
class SandwichTestNew(unittest.TestCase):
def test_subSandwich_new(self):
result = subSandwich_new('catcowcat', 'cat')
self.assertEqual(result, 9)
def test_subSandwich_new2(self):
result = subSandwich_new('catcowcat', 'cow')
self.assertEqual(result, 3)
def test_subSandwich_new3(self):
result = subSandwich_new('ccatcowcatxx', 'cat')
self.assertEqual(result, 9)
def test_subSandwich_new4(self):
result = subSandwich_new('cat', 'cat')
self.assertEqual(result, 3)
def test_subSandwich_new5(self):
result = subSandwich_new('cat', 'cow')
self.assertEqual(result, 0)发布于 2016-04-09 12:09:05
不按特定顺序:
pos、start和end参数提供默认参数,比如: def subSandwich(word、char、pos=0、start=0、end=0),如果我想按原样使用它,我必须在第一个调用时提供0,0,0。这是向用户公开不必要的实现细节。string模块混淆。pos参数,很少接触start或end参数。一个更整洁的递归可能只需要在两个字符串之间传递,然后慢慢地削减text变量的大小,直到它匹配为止。这将允许您使用startswith()和endswith()方法,而IMO则稍微整洁一些。下面是这样重写函数的方法: def sub_sandwich(文本,子):“”返回以sub开头和结尾的text最大子字符串的长度。如果sub不在text中,则返回0。“”#空字符串不能有任何子字符串,如果不是文本:返回0如果text.startswith(sub)和text.endswith( sub):返回len(text) elif text.startswith( sub):返回sub_sandwich(text*-1,sub),否则:返回sub_sandwich(text1:,sub)https://codereview.stackexchange.com/questions/121993
复制相似问题