""" 10. 将上诉2个列表组合成新的列表,包含5个英文名 第一个列表为first name,第二个列表作为family name,xingshir 形式如下:‘andew’, 'steven': A.Steven """ ls1 = ['tom', 'andew', 'jack', 'jeef'] ls2 = ['steven', 'bill', 'alice', 'jennief', 'eve'] l1 = [i[0].capitalize() for i in ls1] # print(l1) l2 = [i.capitalize() for i in ls1] l = [] for index in range(len(l1)): l.append('.'.join((l1[index], l2[index]))) print(l) E:\myprogram\anaconda\python.exe E://Python/python.py ['T.Tom', 'A.Andew', 'J.Jack', 'J.Jeef'] """ 11. 编写一个函数, 可以任意接受多个整数参数,函数返回一个元祖,包含所有接受整数的平均值和最大值 """ """ 12. 给定一个字符串,找出不含重复字符的最大子串长度和最长字符串 """ # 方法1:采用集合特性:无重复元素 def max_str1(str): if len(str) == 1: return str, 1 else: s = set() maxlen, sub = 0, '', for j in range(len(str)): s.add(str[j]) maxlen = len(s) sub = s return sub, maxlen string = 'aacdefxabcdaaaadbdexxzzxcvsdfadsgfhgfh' print(max_str1(string)) E:\myprogram\anaconda\python.exe E://Python/python.py ({'x', 'c', 'd', 'a', 'v', 's', 'e', 'f', 'g', 'b', 'z', 'h'}, 12) # 方法2:采用滑动窗口思想 (这个解法有点问题) 问题出在哪?欢迎留言解决 def max_str(str): if len(str) == 1: return str, 1 res, max_len = '', 0 i = 0 for j in range(1, len(str)): # 创建滑动窗口 sub = str[i:j+1] # 判断窗口里的元素是否相等 if sub[-1] != sub[-2]: # 若窗口长度大于字符子串长度,就更换 if len(sub) > max_len: res, max_len = sub, len(sub) # 窗口里的元素相等,就将窗口起始i位置变到目前j的位置上 else: i = j return res, max_len string = 'aacdefxabcdaaaadbdexxzzxcvsdfadsgfhgfh' print(max_str(string)) ('zxcvsdfadsgfhgfh', 16) Process finished with exit code 0 # 方法3:采用堆栈思想完成检索(这个解法有点问题) 问题出在哪?欢迎留言解决 def fun3(str): stack, res, max_len = [], '', 0 for s in str: if len(stack) == 0: stack.append(s) else: if stack[-1] != s: stack.append(s) if len(stack) > max_len: res, max_len = ''.join(stack), len(stack) else: stack = [s] return res, max_len string = 'aacdefxabcdaaaadbdexxzzxcvsdfadsgfhgfh' print(fun3(string))
######针对题12给出易理解并正确的代码(窗口+双指针):
def fun4(self, s: str):
##设定初始双指针
head, tail = 0, 0
##设定初始无重复字符子串长度
sub = 0
if len(s)==0 and len(s)==1:
return len(s)
while tail < len(s):
##若tail指针对应的元素不在窗口内,窗口尾指针向后移动并更新子串长度
if s[tail] not in s[head:tail]:
tail+=1
sub = max(sub, len(s[head:tail]))
##若tail指针对应的元素在窗口内,窗口头指针向后移动
else:
head+=1
return sub
('zxcvsdfadsgfhgfh', 16)
Process finished with exit code 0