假币问题:
这里假币默认比真币轻,而且是每次比较两堆,即一个天平。
def compare(coinA, coinB): #比较两堆硬币的重量
if sum(coinA) < sum(coinB):
result = 'left'
elif sum(coinA) > sum(coinB):
result = 'right'
else:
result = 'eqal'
return result
def split(coin,n): #分割coin硬币为两堆
coinA = coin[0: n // 2]
coinB = coin[n // 2: n]
return coinA, coinB
def Judge(coin,index): #判断硬币中假币的位置
n = len(coin)
if n == 0:
print('no coins')
elif n == 1:
print(' fake coin index:', index)
elif n == 2:
if coin[0] < coin[1]:
print('fake coin index:', index)
else:
print('fake coin index:', index+1)
elif n % 2 == 0 and n > 2:
coinA, coinB = split(coin, n)
result = compare(coinA, coinB)
if result == 'left':
coin = coinA
Judge(coin, index)
elif result == 'right' :
index += n / 2
coin = coinB
Judge(coin, index)
else:
print(n)
elif n % 2 == 1 and n > 2:
coinA,coinB = split(coin, n-1)
result = compare(coinA, coinB)
if result == 'eqal':
print('fake coin index:', index)
else:
if result == 'left':
coin = coinA
Judge(coinA, index)
else:
index += (n-1) / 2
coin = coinB
Judge(coinB, index)
#设置假币数组,当然你可以随机生成,生成的假币比真币轻,而且真币质量相等
coin = [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 9, 10, 10, 10, 10, 10]
index = 0
print(coin)
Judge(coin, index)
算法
input:真假币组成的数组,其值为质量,假币默认为轻。事先不知各个重量
output:假币下标
function:compare()//比较两堆硬币的质量
function:coinA, coinB = split()//分割硬币为两堆
Judge()// 主函数,参数为硬币和下标
n = 硬币个数
if n == 0
没有硬币
elif n ==1
该币为假币
elif n == 2
compare()
假币为较轻者
elif n % 2 == 0 and n > 2
compare()
if 假币在A堆里
Judge(coinA,index)
elif 假币在B堆里
Judge(coinB,index)
else 此时先取出末尾一个硬币,使其数量为偶
compare()
if 两堆硬币质量相等
假币为取出的那个
else
coinA,coinB中较轻者另其为coin
Judge(coin,index)