9

我需要编写一个函数来计算所有数字 n 的总和。

Row 1:          1 
Row 2:         2 3 
Row 3:        4 5 6 
Row 4:       7 8 9 10 
Row 5:     11 12 13 14 15 
Row 6:   16 17 18 19 20 21 

将上述行想象为“数字三角形”会有所帮助。该函数应该采用一个数字 n,它表示要使用多少个数字以及使用哪一行。第 5 行的总和是 65。如何让我的函数对任何 n 值进行此计算?

为了清楚起见,这不是家庭作业。那是在最近的期中考试,不用说,我被难住了。

4

6 回答 6

14

The leftmost number in column 5 is 11 = (4+3+2+1)+1 which is sum(range(5))+1. This is generally true for any n.

So:

def triangle_sum(n):
    start = sum(range(n))+1
    return sum(range(start,start+n))

As noted by a bunch of people, you can express sum(range(n)) analytically as n*(n-1)//2 so this could be done even slightly more elegantly by:

def triangle_sum(n):
    start = n*(n-1)//2+1
    return sum(range(start,start+n))
于 2012-10-11T17:16:36.193 回答
4

使用方程式的解决方案,但要得出该方程式需要做一些工作。

def sumRow(n):
    return (n**3+n)/2
于 2012-10-11T17:25:46.667 回答
2

The numbers 1, 3, 6, 10, etc. are called triangle numbers and have a definite progression. Simply calculate the two bounding triangle numbers, use range() to get the numbers in the appropriate row from both triangle numbers, and sum() them.

于 2012-10-11T17:16:25.890 回答
0
def sum_row(n):
    final = n*(n+1)/2
    start = final - n
    return final*(final+1)/2 - start*(start+1)/2

or maybe

def sum_row(n):
    final = n*(n+1)/2
    return sum((final - i) for i in range(n))

How does it work:

The first thing that the function does is to calculate the last number in each row. For n = 5, it returns 15. Why does it work? Because each row you increment the number on the right by the number of the row; at first you have 1; then 1+2 = 3; then 3+3=6; then 6+4=10, ecc. This impy that you are simply computing 1 + 2 + 3 + .. + n, which is equal to n(n+1)/2 for a famous formula.

then you can sum the numbers from final to final - n + 1 (a simple for loop will work, or maybe fancy stuff like list comprehension) Or sum all the numbers from 1 to final and then subtract the sum of the numbers from 1 to final - n, like I did in the formula shown; you can do better with some mathematical operations

于 2012-10-11T17:18:41.893 回答
0

这是一个通用的解决方案:

start=1
n=5
for i in range(n):
    start += len (range(i))
answer=sum(range(start,start+n))

作为一个函数:

def trio(n):
    start=1
    for i in range(n):
            start += len (range(i))
    answer=sum(range(start,start+n))
    return answer
于 2012-10-11T17:19:31.397 回答
0
def compute(n):
   first = n * (n - 1) / 2 + 1
   last = first + n - 1
   return sum(xrange(first, last + 1))
于 2012-10-11T17:29:05.077 回答