程序填空题:三分递归找假硬币 - 实验14 用三分法找假硬币 - 《Python编程基础及应用实验教程》- 高教社
三分法找假硬币的算法工作原理,请查询《Python编程基础及应用实验教程》之实验14.
请将下述程序补充完整,使其可以找出假硬币。该程序是递归的。
<br>
python
from math import ceil
def findFalseCoin(coins,idxStart,iLength):
if iLength == 1:
return idxStart
n = ceil(iLength/3)
wPart1 = sum(coins[idxStart:idxStart+n])
wPart2 = sum(coins[])
wPart3 = sum(coins[idxStart+2*n:])
if wPart1 < wPart2:
return findFalseCoin(coins,idxStart,n)
elif wPart1 > wPart2:
return findFalseCoin()
else:
return findFalseCoin()
if __name__ == '__main__':
coins = [100,100,100,100,100,100,100,100,100,100,100]
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空:idxStart+n:idxStart+2*n
第2空:idxStart+iLength
第3空:coins,idxStart+n,n
第4空:coins,idxStart+2*n,iLength-2*n
第5空:coinsCopy, 0, len(coinsCopy)
请将下述程序补充完整,使其可以找出假硬币。该程序是递归的。
<br>
python
from math import ceil
def findFalseCoin(coins,idxStart,iLength):
if iLength == 1:
return idxStart
n = ceil(iLength/3)
wPart1 = sum(coins[idxStart:idxStart+n])
wPart2 = sum(coins[])
wPart3 = sum(coins[idxStart+2*n:])
if wPart1 < wPart2:
return findFalseCoin(coins,idxStart,n)
elif wPart1 > wPart2:
return findFalseCoin()
else:
return findFalseCoin()
if __name__ == '__main__':
coins = [100,100,100,100,100,100,100,100,100,100,100]
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空:idxStart+n:idxStart+2*n
第2空:idxStart+iLength
第3空:coins,idxStart+n,n
第4空:coins,idxStart+2*n,iLength-2*n
第5空:coinsCopy, 0, len(coinsCopy)