十二球称重问题的 Python 程序 bug 修正版

本文提供了一个修正后的Python程序,用于解决12个球中找出发重不同球的问题。程序通过多次称重策略,确保最多3次找出不同重量的球。详细步骤包括初始化球的重量,进行多次比较并分析结果,最后给出具体解决方案。
摘要由CSDN通过智能技术生成
题目是这样的:
  12个球,其中一个质量和其余的不同,用一个无砝码的天平最多分3次称出。以前考虑过,但最终得出了一个错误的结论。这次应 quanben 之请再想了一下,大致如下解法:

# vim: set sts=4 ts=4 sw=4 et:
# twlvball.py: solves the twelve balls problem.

import sys
import operator

class Ball():
    def __init__(self, num, w):
        self.num = num
        self.weight = w

def main():
    print "This program is fragile. Try not to enter wrong arguments."
    sys.stdout.write("ball number[0-11]: ")
    num = int(sys.stdin.readline().rstrip())
    assert 0 <= num and num < 12
    sys.stdout.write("weight[h/l]: ")
    w = sys.stdin.readline().rstrip()
    assert w in ["h", "l"]
    test(num, w)

def test(num, w):
    balls = []
    for i in range(12):
       
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值