Python-nowcoder百鸡问题&Digital Roots

这篇博客探讨了如何使用Python解决百鸡问题,即如何用不同价格的鸡组合成100只,并给出了多种可能的解。同时,文章还介绍了数字根的概念,解释了其计算方法,并分享了在编程实现过程中遇到的问题和解决方案,包括输入处理和循环条件的设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

用小于等于n元去买100只鸡,大鸡5元/只,小鸡3元/只,还有1/3元每只的一种小鸡,分别记为x只,y只,z只。编程求解x,y,z所有可能解。

输入描述:
测试数据有多组,输入n。
输出描述:
对于每组输入,请输出x,y,z所有可行解,按照x,y,z依次增大的顺序输出。
输入
40
输出
x=0,y=0,z=100
x=0,y=1,z=99
x=0,y=2,z=98
x=1,y=0,z=99

解题思路

1、首先列出公式(x+y+z == 100) & (5*x + 3*y + 1/3*z <= n)
2、其次看清对于输入和输出的要求,多次打印的话,直接在函数里进行print输出,调用时不打印即可

def hundredChicken(n):
	for x in range(101):
		for y in range(101):
			for z in range(101):
				if (x+y+z == 100) & (5*x + 3*y + 1/3*z <= n):
					print("x="+str(x)+",", "y="+str(y)+",", "z="+str(z))
try:
	num = int(input())
	hundredChicken(num)
except Exception:
	pass
题目描述

The digital root of a positive integer is found by summing the digits of the integer. If the resulting value is a single digit then that digit is the digital root. If the resulting value contains two or more digits, those digits are summed and the process is repeated. This is continued as long as necessary to obtain a single digit. For example, consider the positive integer 24. Adding the 2 and the 4 yields a value of 6. Since 6 is a single digit, 6 is the digital root of 24. Now consider the positive integer 39. Adding the 3 and the 9 yields 12. Since 12 is not a single digit, the process must be repeated. Adding the 1 and the 2 yeilds 3, a single digit and also the digital root of 39.

解题思路

一、采用模九法,以下是踩坑点:
在这里插入图片描述
正确的公式为:(num + 8) % 9 + 1
在这里插入图片描述
遇到问题:输入后没有输出,原因为输入的是字符串,而判断的只是整数
在这里插入图片描述
遇到问题:只能输入且判断一次,原因为缺少while true,若没有break搭配while true使用则会一直循环下去
在这里插入图片描述
故使用模九法的最终答案是:

def DigitalRoot(num):
	while num >= 0:
		root = (num + 8) % 9 + 1
		return root
	else:
		print("不能为负数")

try:
	while True:
		n = int(input())
		print(DigitalRoot(n))
except Exception:
	pass

二、判断数字的长度,若大于1(非个位数)则通过循环进行相加

while True:
    try:
        strs = input().strip()
        while len(strs)>1:
            numsum=0
            for strone in strs:
                numsum+=int(strone)
            strs=str(numsum)
        print(numsum)
    except:
        break
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值