Python-nowcoder百鸡问题&Digital Roots

题目描述

用小于等于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.

解题思路

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

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