1

I was trying figure out if there is a more efficient way to code it but i couldn't. Could anyone please help me to figure out if there is a more efficient way to code it?

So here is the code:

def iterative(n): 
     sum = 0 
     for i in range(1,n+1): 
         form = i*(i+1)**2 
         sum = sum + form
     return(sum)

Thanks in advance!

2 Answers2

4

If you mean shorter, then:

def iterative(n):
    return sum(i * (i + 1) ** 2 for i in range(1, n + 1))


print(iterative(10))

made some efficiency testing with all the answers here:

def iterative1(n):
    return sum(i * (i + 1) ** 2 for i in range(1, n + 1))


def iterative2(n):
    sum = 0
    for i in range(1, n + 1):
        form = i * (i + 1) ** 2
        sum = sum + form
    return (sum)

def iterative3(n):
    return sum(map(lambda i: i*(i+1)**2, range(1,n+1)))

import time

x = time.time()
print(iterative1(10000000))
print( time.time() - x) # 5.313434600830078

x =  time.time()
print(iterative2(10000000))
print(time.time() - x) # 5.021821975708008

x =  time.time()
print(iterative3(10000000))
print(time.time() - x) # 5.61063551902771

seems like your is the fastest(but less readable IMO)

nonamer92
  • 1,887
  • 1
  • 13
  • 24
  • 1
    I'd remove the `[` and `]` for memory efficiency (so that no list needs to be allocated). – Seb Nov 30 '19 at 16:41
  • Very appreciate the answer. But do you or anyone have any idea to make it to ask the n value to the user to be entered? When i tried to do it just keeps me giving an error. –  Nov 30 '19 at 16:44
  • use the input function, I can fix my answer, but you need to try yourself – nonamer92 Nov 30 '19 at 16:45
  • read about it here: https://snakify.org/en/lessons/print_input_numbers/ – nonamer92 Nov 30 '19 at 16:45
1

If you are truly looking for speed, you could just do the math and remove the iterative aspect from it. Sums of polynomials can be broken into sums of sums and those small sums can be solved directly with something like this (just be careful of float precision if the number will be huge):

def iterative4(n):
        return (n * (n + 1)//2)**2 + (n * (n + 1) * (2 * n + 1))//3 +  (n * (n + 1))//2

Here for example, it is several orders of magnitude faster — you could calculate the value with n = 10000000 roughly 15000 times in the time it takes the iterative approach to do it once:

def iterative1(n):
    return sum(i * (i + 1) ** 2 for i in range(1, n + 1))

def iterative4(n):
    return (n * (n + 1)//2)**2 + (n * (n + 1) * (2 * n + 1))//3 +  (n * (n + 1))//2


x =  time.time()
print(iterative4(10000000))
print(time.time() - x) 

#2500001166666841666675000000
#0.00030493736267089844

x =  time.time()
print(iterative1(10000000))
print(time.time() - x)

#2500001166666841666675000000
#4.789726972579956
Mark
  • 90,562
  • 7
  • 108
  • 148