简体   繁体   English

Python 中一个序列的和

[英]Sum of a sequence in Python

Let me present my problem in mathematical notation before diving into the programming aspect.在深入编程方面之前,让我用数学符号展示我的问题。

Let a_n be the sequence whose i th term is defined as i^2 - (i-1)^2 .a_n为其第i项定义为i^2 - (i-1)^2的序列。 It is easy to see a_i = 2i-1 .很容易看出a_i = 2i-1 Hence (in mathematical notation) we have a_n = {2-1, 4-1, ..., 2n-1} = {1, 3, 5, ..., 2n -1} , the sequence of all odd integers in the range [1, 2n] .因此(用数学符号)我们有a_n = {2-1, 4-1, ..., 2n-1} = {1, 3, 5, ..., 2n -1} ,所有奇数的序列在[1, 2n]范围内。

In HacerRank, an excercise is to define a function that computes the sum S_n = a_1 + a_2 +... + a_n and then finds x in the equation S_n = x (mod 10^9 + 7) (still using math notation).在 HacerRank 中,一个练习是定义一个 function 来计算总和S_n = a_1 + a_2 +... + a_n ,然后在等式S_n = x (mod 10^9 + 7)中找到x (仍然使用数学符号)。 So we need to find the equivalence of the sum of all odd integers up to 2n in mod 10^9 + 7 .因此,我们需要在mod 10^9 + 7中找到2n的所有奇数之和的等价性。

Now, to go into the programming aspect, here's what I attempted:现在,go 进入编程方面,这是我尝试的:

def summingSeries(n):
    # Firstly, an anonimous function computing the ith term in the sequence.
    a_i = lambda i: 2*i - 1
    
    # Now, let us sum all elements in the list consisting of
    # every a_i for i in the range [1, n].
    s_n = sum([a_i(x) for x in range(1, n + 1)])

    # Lastly, return the required modulo.
    return s_n % (10**9 + 7)

This function passes some , but not all tests in HackerRank.这个 function 通过了 HackerRank 中的一些测试,但不是所有测试。 However, I am oblivious as to what might be wrong with it.但是,我不知道它可能有什么问题。 Any clues?有什么线索吗?

Thanks in advance.提前致谢。

The solution ended being quite simple.解决方案非常简单。 The tests were being failed not because the logic of the code was wrong, but because it was taking too long to compute.测试失败不是因为代码逻辑错误,而是因为计算时间太长。 Observing that 1 + 3 +... + 2n-1 = n^2 we can write the function as观察到1 + 3 +... + 2n-1 = n^2我们可以将 function 写成

def summingSeries(n):
    return n**2 % (10**9 + 7)

which is clearly a major simplification.这显然是一个重大的简化。 The runtime is now acceptable according to HackerRank's criteria and all tests were passed.根据 HackerRank 的标准,运行时现在是可以接受的,并且所有测试都已通过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM