程序填空题:三分非递归找假硬币 - 实验14 用三分法找假硬币 - 《Python编程基础及应用实验教程》- 高教社
三分非递归查找假硬币的算法请查询《Python编程基础及应用实验教程》实验14。
python
from math import ceil
def findFalseCoin(coins):
#查找范围:从idxStart下标开始的iLength个硬币
idxStart, iLength =
while True:
if iLength == 1:
return idxStart
n = ceil(iLength/3)
wPart1 = sum(coins[idxStart:idxStart+n])
wPart2 = sum(coins[])
wPart3 = sum(coins[])
if wPart1 < wPart2:
idxStart, iLength = idxStart, n
elif wPart1 > wPart2:
idxStart, iLength =
else:
idxStart, iLength =
if __name__ == '__main__':
coins = [100]*11
for i in range(len(coins)):
coinsCopy = coins[:]
coinsCopy[i] = 99
r = findFalseCoin()
print(f'False coin idx:{r}, weight:{coinsCopy[r]}')
期望的执行结果为:
False coin idx:0, weight:99
False coin idx:1, weight:99
False coin idx:2, weight:99
False coin idx:3, weight:99
False coin idx:4, weight:99
False coin idx:5, weight:99
False coin idx:6, weight:99
False coin idx:7, weight:99
False coin idx:8, weight:99
False coin idx:9, weight:99
False coin idx:10, weight:99
<br>**拼尽全力还是不会?参考B站习题讲解**<br>
哔哩哔哩up主:[海洋饼干叔叔](https://space.bilibili.com/384177380) [Python课程](https://www.bilibili.com/video/BV1kt411R7uW/)
[Python习题](https://www.bilibili.com/video/BV1iL411t7UZ/)
[简洁的C和C++](https://www.bilibili.com/video/BV1it411d7zx/)
作者每天分享一篇关于C/C++/Python的技术文章,学习编程不迷路。
![image.png](~/7c4cfd2d-8e3e-40cd-826d-299d4200e600.png)
答案:
第1空:0, len(coins)
第2空:idxStart+n:idxStart+2*n
第3空:idxStart+2*n:idxStart+iLength
第4空:idxStart+n, n
第5空:idxStart+2*n, iLength-2*n
第6空:coinsCopy
python
from math import ceil
def findFalseCoin(coins):
#查找范围:从idxStart下标开始的iLength个硬币
idxStart, iLength =
while True:
if iLength == 1:
return idxStart
n = ceil(iLength/3)
wPart1 = sum(coins[idxStart:idxStart+n])
wPart2 = sum(coins[])
wPart3 = sum(coins[])
if wPart1 < wPart2:
idxStart, iLength = idxStart, n
elif wPart1 > wPart2:
idxStart, iLength =
else:
idxStart, iLength =
if __name__ == '__main__':
coins = [100]*11
for i in range(len(coins)):
coinsCopy = coins[:]
coinsCopy[i] = 99
r = findFalseCoin()
print(f'False coin idx:{r}, weight:{coinsCopy[r]}')
期望的执行结果为:
False coin idx:0, weight:99
False coin idx:1, weight:99
False coin idx:2, weight:99
False coin idx:3, weight:99
False coin idx:4, weight:99
False coin idx:5, weight:99
False coin idx:6, weight:99
False coin idx:7, weight:99
False coin idx:8, weight:99
False coin idx:9, weight:99
False coin idx:10, weight:99
<br>**拼尽全力还是不会?参考B站习题讲解**<br>
哔哩哔哩up主:[海洋饼干叔叔](https://space.bilibili.com/384177380) [Python课程](https://www.bilibili.com/video/BV1kt411R7uW/)
[Python习题](https://www.bilibili.com/video/BV1iL411t7UZ/)
[简洁的C和C++](https://www.bilibili.com/video/BV1it411d7zx/)
作者每天分享一篇关于C/C++/Python的技术文章,学习编程不迷路。
![image.png](~/7c4cfd2d-8e3e-40cd-826d-299d4200e600.png)
答案:
第1空:0, len(coins)
第2空:idxStart+n:idxStart+2*n
第3空:idxStart+2*n:idxStart+iLength
第4空:idxStart+n, n
第5空:idxStart+2*n, iLength-2*n
第6空:coinsCopy