简体   繁体   中英

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 . It is easy to see 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] .

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). So we need to find the equivalence of the sum of all odd integers up to 2n in mod 10^9 + 7 .

Now, to go into the programming aspect, here's what I attempted:

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. 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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