在八枚外观相同的硬币中,有一枚是假币,并且已知假币与真币的重量不同,但不知道假币与真币相比较轻还是较重。可以通过一架天平来任意比较两组硬币,设计一个高效的算法来检测出这枚假币。
(1) 设计减治算法实现八枚硬币问题;
(2) 设计实验程序,考察用减治技术设计的算法是否高效;
(3) 扩展算法,使之能处理n枚硬币中有1枚假币的问题。
代码:
import numpy as np
def find_feke_coin(coins,star_index=0):
print(coins,star_index)
if len(coins)==1:
#假币
return star_index
if len(coins)%2==0:
#偶序列
group_mid = len(coins) // 2
left_group = coins[:group_mid]
right_group = coins[group_mid:]
left_weight=sum(left_group)
right_wight=sum(right_group)
if left_weight>right_wight:
#假币在重的一边
return star_index+find_feke_coin(left_group,0)
else:
return star_index+find_feke_coin(right_group,group_mid)
else:
#奇序列
mid_index=len(coins)//2
left_group=coins[:mid_index]
right_group=coins[mid_index+1:]
mid_number=coins[mid_index]
print(left_group,mid_number,right_group)
left_weight = sum(left_group)
right_wight = sum(right_group)
if left_weight > right_wight:
# 假币在重的一边
return star_index + find_feke_coin(left_group, 0)
elif left_weight < right_wight:
return star_index + find_feke_coin(right_group,mid_index+1)
else:
#相等,说明假币是中间的哪一个
return star_index+mid_index
def find_EightCoins_fake(coins,star_index=0):
# print(coins,star_index)
if len(coins)==1:
#假币
return star_index
group_mid = len(coins) // 2
left_group = coins[:group_mid]
right_group = coins[group_mid:]
left_weight = sum(left_group)
right_wight = sum(right_group)
if left_weight > right_wight:
# 假币在重的一边
return star_index + find_EightCoins_fake(left_group, 0)
else:
return star_index + find_EightCoins_fake(right_group, group_mid)
def generate_test_cases(num_cases):
test_cases = []
for _ in range(num_cases):
weight=sorted(np.random.choice(list(range(1,11)),size=2,replace=False))
case_i=[weight[0]]*8
fake_index=np.random.choice(range(0,8))
case_i[fake_index]=weight[1]
test_cases.append([case_i,fake_index])
return test_cases
def test(case):
true_rate=0
for i in case:
test_i=find_EightCoins_fake(i[0],0)
if test_i==i[1]:
true_rate+=1
else:
print(i,test_i)
print('正确率为:',true_rate/len(case)*100,'%')
# #8枚
# fake_index=find_EightCoins_fake([1,1,1,1,1,1,2,1],0)
# print('8枚硬币:假币所在位置',fake_index+1)
# #测试
# case=generate_test_cases(20)
# test(case)
# #整合n枚硬币
# fake_index = find_feke_coin([1,1,1,1,1,1,2,1,1,1],0)
# print('假币所在位置',fake_index+1)
# fake_index = find_feke_coin([1,1,2,1,1,1,1,1,1,1],0)
# print('假币所在位置',fake_index+1)