函数基础
计算字符串中某字符个数
1 def countsubstring(s,ch): #s和ch为形参 2 c=0 3 i=0 4 while i<len(s): 5 if s[i]==ch: 6 c +=1 7 i +=1 8 print(c) 9 str=‘wujiadongjiangruisuirsuiuigjsjsiuisldjsjeuiui‘ 10 m=‘i’ 11 countsubstring(s,m) #调用函数传入的参数str和m为实参
计算子串sub个数
1 def countsubstring(s,sub): 2 c=0 3 i=0 4 while i<=len(s)-len(sub): 5 if s[i:i+len(sub)]==sub: 6 c +=1 7 # print(s[i:i+len(sub)]) 8 i +=1 9 print(c) 10 str=‘wujiadongjiangruisuirsuiuigjsjsiuisldjsjeuiui‘ 11 12 countsubstring(str,‘ui‘)
1 def myfind(s,sub): 2 i=0 3 while i<=len(s)-len(sub): 4 if s[i:i+len(sub)]==sub: 5 print(i) 6 break 7 i +=1 8 else: 9 print(‘-1‘) 10 11 str=‘wujiadong‘ 12 sub=‘on‘ 13 myfind(str,sub)
找最大值
1 li=[111,2,3,7,9,76,98,23,45] 2 def myfindmax(M): 3 i=0 4 max=li[0] 5 while i<len(li): 6 if max<li[i]: 7 max=li[i] 8 9 i +=1 10 print(max) 11 myfindmax(li)
找第二大值
#这种情况两个最大都相等时是错误的 1 li=[111,222,333,7,9,765,98,23,45] 2 def max2(t): 3 max1=t[0] 4 max2=t[0] 5 for x in t: 6 if x >max1: 7 max2=max1 8 max1=x 9 else: 10 if x >max2: #这里添加上条件x!=max1 就可避免 11 max2=x 12 print(‘max1‘,max1) 13 print(‘max2‘,max2) 14 max2(li)
删除某个值
#有bug,有重复的值不能删除 1 li=[1,2,3,4,5,6,7,8,9] 2 def delvalue(t): 3 global li #没懂为什么一定要加这个 4 i=0 5 while i<len(li): 6 if li[i]==t: 7 left=li[:i] 8 print(left) 9 right=li[i+1:] 10 # print(i) 11 li=left+right 12 i +=1 13 14 delvalue(6)
删除所有的值
时间: 2024-10-07 12:53:07