【基础入门题】2021.11.28
10个小孩围成一圈分糖果,老师分给第1个小孩10块,第2个小孩2块,第3个小孩8块,第4个小孩22块,第5个小孩16块,第6个小孩4块,第7个小孩10块,第8个小孩6块,第9个小孩14块,第10个小孩20块。然后所有的小孩同时将手中的糖分一半给右边的小孩;糖块数为奇数的人可向老师要一块。问:经过几轮操作所有小孩手中的糖块数一样多,糖果的块数都是几?
编程语言:包括但不限于Python
题目来源:派森特给站每日刷题频道
————————————————
方法一: while条件,取列表某一元素*列表长度与原列表比较
candy = [10,2,8,22,16,4,10,6,14,20] count = 0 size = len(candy) print(count,candy) while [candy[0]]*size!=candy: count += 1 mid = [0] for i in range(size): t = (candy[i]+1)//2 #不管是否偶数都加1后整除2,事实偶数的等于没要那一颗 mid.append(t) #每个小朋友的一半糖果数先暂存起来 candy[i] = t mid[0] = mid[-1] #第一个小朋友拿最后一个的,相当于围成一圈 for i in range(size): candy[i] += mid[i] #都加上左边小朋友的一半糖数 print(count,candy) print(f'经过{count}次,大家的糖都是{candy[0]}块。')
运行结果:
0 [10, 2, 8, 22, 16, 4, 10, 6, 14, 20]
1 [15, 6, 5, 15, 19, 10, 7, 8, 10, 17]
2 [17, 11, 6, 11, 18, 15, 9, 8, 9, 14]
3 [16, 15, 9, 9, 15, 17, 13, 9, 9, 12]
4 [14, 16, 13, 10, 13, 17, 16, 12, 10, 11]
5 [13, 15, 15, 12, 12, 16, 17, 14, 11, 11]
6 [13, 15, 16, 14, 12, 14, 17, 16, 13, 12]
7 [13, 15, 16, 15, 13, 13, 16, 17, 15, 13]
8 [14, 15, 16, 16, 15, 14, 15, 17, 17, 15]
9 [15, 15, 16, 16, 16, 15, 15, 17, 18, 17]
10 [17, 16, 16, 16, 16, 16, 16, 17, 18, 18]
11 [18, 17, 16, 16, 16, 16, 16, 17, 18, 18]
12 [18, 18, 17, 16, 16, 16, 16, 17, 18, 18]
13 [18, 18, 18, 17, 16, 16, 16, 17, 18, 18]
14 [18, 18, 18, 18, 17, 16, 16, 17, 18, 18]
15 [18, 18, 18, 18, 18, 17, 16, 17, 18, 18]
16 [18, 18, 18, 18, 18, 18, 17, 17, 18, 18]
17 [18, 18, 18, 18, 18, 18, 18, 18, 18, 18]
经过17次,大家的糖果都是18块。
方法二:while条件:列表与倒序的和排序后的都相等即完成任务
candy = [10,2,8,22,16,4,10,6,14,20] count = 0 size = len(candy) print(count,candy) while not candy==candy[::-1]==sorted(candy): count += 1 mid = [0] for i in range(size): t = (candy[i]+1)//2 #不管是否偶数都加1后整除2,事实偶数的等于没要那一颗 mid.append(t) #每个小朋友的一半糖果数先暂存起来 candy[i] = t mid[0] = mid[-1] #第一个小朋友拿最后一个的,相当于围成一圈 for i in range(size): candy[i] += mid[i] #都加上左边小朋友的一半糖数 print(count,candy) print(f'经过{count}次,大家的糖都是{candy[0]}块。')