python之男票管理系统(题目源自2019华为杯)
话不多说,看题:
参考代码:
#encoding:utf-8
#输入T组数据
def changeLocation(List):
global counts
tempCount = 0
while List != sorted(List,reverse=True): #排列完毕后应该和sorted()降序是一样的
for i in range(len(List)-1):
if List[i] < List[i+1]:
List[i],List[i+1] = List[i+1],List[i]
tempCount+=1
#排列完毕,此时tempCount为本组数据交换次数
counts.append(tempCount)
T = eval(input())
counts = [] #存储每一组数据的交换次数
for i in range(T):
likes = [] #存储好感度,注意每个男生的好感度不能相同!
n = int(input()) #输入男票数量
for j in range(n):
likes.append(eval(input()))
changeLocation(likes)
for i in range(len(counts)):
print("Case #"+str(i+1)+": "+str(counts[i]))
小技巧:其实本题如果没有限制每次只能交换相邻两人的好感度的话,笔主真的想一个sort()函数解决所有烦恼。
但殊途同归,最后的结果无外乎是排列完毕的列表 == sorted(列表,reverse=True)
这里可能会有人问为什么不用sort()函数 like this :
列表 == 列表.sort(reverse = True)?
咱们试试:
显然,sort()函数是不行的,我们查看一下二者的type
sorted()函数返回的是list类型,而sort()函数返回一个NoneType类型,所以这里我们不用sort()函数,同时也注意,在进行for循环遍历时也不要使用sort()函数。