有一位农场主的遗嘱:第1个儿子分100美元和剩下财产的10%,第二个分……结果分的一样多,问有几个儿子?,10%,解题#Encoding=


解题

#Encoding=UTF-8#!/usr/bin/python#一位农场主的遗嘱上写道他死后:第1个儿子分100美元和剩下财产的10%;#第1个儿子分200美元和剩下财产的10%;第3个儿子分300美元和剩下财产的10%;#第4个儿子分400美元和剩下财产的10%……结果每个儿子分的一样多,问有几个儿子?#完全符合PEP8标准,但代码由于研究需要,因此较乱,欢迎整理,欢迎优化!import timedef son_test(child_num, max_dollars):    max_dollars += 1    cache = dollars_cracker(child_num, max_dollars)    if cache != None:        return cache    else:        return Nonedef dollars_cracker(son, dollars):    def test(dollars, son):        now_dollars = 0        while_son = 0        while while_son != son:            while_son += 1            #now_dollars +=\            #        100 * while_son + \            #           (dollars-now_dollars-100*while_son)*0.1            #化简后得出:            now_dollars += \                    90 * while_son + 0.1 * dollars - 0.1 * now_dollars        if dollars == now_dollars:            return 1        else:            return 0    for i in xrange(1, dollars + 1):        if test(i, son) == 1:            return idef main():    for i in xrange(4, 10):        cache = son_test(i, 10000)        if cache != None:            print u'通过分别尝试4-9个儿子,共1-9999美元遗产得出:'            print u'共有', i, u'个儿子,', cache, u'美元财产。'            break#可以使用profile进行分析哦!#import profile#profile.run("main()")starttime = time.clock()main()endtime = time.clock()print u'解题耗时约:', endtime - starttime, u'秒。'

评论关闭