Python solves the problem of buying chickens: 3 cents can buy 1 rooster, 2 cents can buy a hen, 1 cent can buy 3 chicks. If you buy 100 chickens for 100 cents, how many roosters, hens, and chickens are there?

code show as below:

#coding: utf-8
#题目描述: 3文钱可以买1只公鸡,2文钱可以买一只母鸡,1文钱可以买3只小鸡。用100 文 钱买100 只鸡,那么各有公鸡、母鸡、小鸡多少只?

for i in range(35): #100文钱公鸡的数量肯定不会超过34只
    for j in range(51): #100文钱母鸡的数量肯定不会超过50只
        for z in range(101): #小鸡便宜,但是只能买100只鸡,所以小鸡最多只是有可能买100只
            if z%3 == 0: #这里做个判断,因为1文钱可以买3只小鸡,所以买的小鸡的只数肯定是3的倍数
                sum = i + j + z #买的鸡的总数
                SUM = 3*i + 2*j + z/3 #买鸡花的钱的总数
                if sum == 100 and SUM == 100: #当满足了买鸡100只,同时花了100文钱,条件成立,输出各种鸡的个数
                    print("公鸡: %d, 母鸡: %d, 小鸡: %d" %  (i, j, z))

The output is as follows:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44901564/article/details/106378356