假币问题python

​​​​​​​假币问题:

 

  这里假币默认比真币轻,而且是每次比较两堆,即一个天平。

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)
			
			

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Alocus_

如果我的内容帮助到你,打赏我吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值