0

I want to create a function so that it will find the integer a so that a <= n.

If n is 99, then the program will return a = 3. This is because the function is finding the sums of the consecutive cubes. So, 1 + 8 + 27 + 64 = 100, which is more than 99. But 1 + 8 + 27 is less than 99, so a = 3 is the correct answer.

I was trying to do something like:

cubes = 0
for i in xrange(1, 1+x)
     cubes += i*i*i
while cubes <= n

but I am very confused. How should I proceed?

4

3 回答 3

6

首先用for循环替换while循环:

cubes, i = 0, 0
while cubes <= n:
    i += 1
    cubes += i ** 3

然后,在循环之后,减去最后一个立方体,因为你已经超过了 limit n

cubes -= i ** 3

i仍然具有它在循环中的最终值。

或者,您可以在一个循环中完成所有操作,首先将 的新值计算cubes为临时变量,然后仅cubes在未超过限制时更新:

cubes, i = 0, 0
while True:    # infinite loop
    i += 1
    new_cubes = cubes + i ** 3
    if new_cubes > n:
        break
    else:
        cubes = new_cubes
于 2013-10-18T12:39:03.710 回答
1

使用itertools.countand 一个 for 循环:

from itertools import count
def solve(n, pow):
    total = 0
    for i in count(1):
        if total + i**pow > n:
            return i-1
        total += i**pow

演示

>>> solve(99, 3)
3
>>> solve(50, 2)
4
于 2013-10-18T12:47:45.680 回答
0

这就是我的做法。

def cubes(n=1):
  while True:
    yield n ** 3
    n += 1

def sum(array):
  total = 0
  for item in array:
    total += item
    yield total

def sum_cubes_lt(n):
  for i, sum in enumerate(sum(cubes()):
    if sum > n:
      return i

# prints '3'
print sum_cubes_lt(99)
于 2013-10-18T12:44:42.130 回答