Python 编程题 第十二节:柠檬水找零、统计数字、合并排序数组、插入5、字符串置换
柠檬水找零
贪心算法
bills=[5,5,10,5,20,10,20]
def zhaoling(bills):
five=0
ten=0
for i in bills:
if i==5:
five+=1
elif i==10:
if five==0:
return False
else:
five-=1
ten+=1
else:
if five>0 and ten>0:#优先找零一个5元和一个10元
five-=1
ten-=1
elif five>=3:
five-=3
else:
return False
return True
print(zhaoling(bills))
统计数字
字符串的.count()方法,统计字符出现次数
def tongji(k,n):
count=0
for i in range(0,n+1):
time=str(i).count(str(k))
count+=time
return count
print(tongji(3,20))
合并排序数组
双指针
def sort(lst1,lst2):
point1=0
point2=0
ans=[]
while point1<len(lst1) and point2<len(lst2):
if lst1[point1]<lst2[point2]:
ans.append(lst1[point1])
point1+=1
else:
ans.append(lst2[point2])
point2+=1
if point1==len(lst1):
ans.extend(lst2[point2:])
else:
ans.extend(lst2[point1:])
return ans
lst1=[1,2,4,8,9]
lst2=[3,4,5,7,10,11,12,12]
print(sort(lst1,lst2))
插入5
插入5使数字最大
def insert(num):
s=str(num)
if num>=0:
ans = ""
flag=False
for i in s:
if int(i)<5 and flag==False:
ans+="5"
flag=True
ans+=i
else:
ans="-"
flag=False
for i in s[1:]:
if int(i)>5 and flag==False:
ans+="5"
flag=True
ans+=i
return ans
print(insert(-734))
字符串置换
a="abcde"
b="cbdae"
def func(a,b):
a=sorted(a)
b=sorted(b)
return a==b
print(func(a,b))