如何编写解决以下问题的Python程序:
找到两个非负整数,其总和为12,最大化第一个数的乘积,3个乘以第二个数的幂。
答案 0 :(得分:2)
我试过这个,我不知道它最好的方法,但这是我的代码:
max = 0
first_no = None
second_no = None
for x in xrange(0,12):
y = 12 - x
P = x * pow(y, 3)
if P > max:
first_no = x
first_no = y
max = P
print "first no is %s" %(first_no)
print "Second no is %s" %(second_no)
print "Maximum number %s" %(max)
答案 1 :(得分:0)
您无法解决Python内置函数中的方程式,但您可以转换问题,以便计算机可以解决该问题。对于这个特定的例子,有几种方法,但使用循环可能是最容易理解的:
def getNumbers(sum,power):
numberlist = [0,0]
biggest = 0
for i in range (1,sum):
for j in range (1,sum):
if (i+j == sum) and (i*(j**power) > biggest):
numberlist = [i,j]
biggest = i*(j**power)
return numberlist,biggest
list, max = getNumbers(12,3)
print list, max
现在,如果你需要小数位,由于Python的舍入问题,它会变得棘手。为了解决这个问题,我需要很多round()
。并且不要对答案实际上是整数而感到失望。
def getNumbers(sumNumber,powerNumber,decimalPlaces = 2):
numberlist = [0.0,0.0]
biggest = 0
increment = 1.0
for k in range (0, decimalPlaces):
increment /= 10
i = 1.0
while i < sumNumber:
j = 1.0
while j < sumNumber:
if round(i + j, decimalPlaces) == sumNumber and round(i*(j**powerNumber),decimalPlaces*3) > biggest:
numberlist = [round(i,decimalPlaces),round(j,decimalPlaces)]
biggest = round(i*(j**powerNumber),decimalPlaces*powerNumber+1)
j += increment
i += increment
return numberlist,biggest
list, max = getNumbers(12,3,2)
print list, max