0

The question is to take an input = n, then take as many inputs as n and output, like this:

image of formula

Which would mean this:

f(1,1) → 1
f(1,2) → 3
f(1,3) → 6
f(2,2) → 2
f(2,3) → 5
f(3,3) → 3

and

answer = 1 + 3 + 6 + 2 + 5 + 3 = 20 → ans = 1+3+6+2+5+3 = 20

What I came up with is this:

def f(l,r):
     return int((r+l)*(r-l+1)/2)

n=int(input())

def WTF(n):
   ans = 0
   S=set()
   for i in range(n):
       S.add(int(input()))
   for i2 in S:
       for i3 in S:
           if i3>=i2:
                ans += f(i2,i3)
   return ans

print(WTF(n))

But it was not accepted due to exceeding a time limit of 1 sec.

How can I make this run faster?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 2
    Your title asks two very different questions: How to make this code faster, and how to measure performance. Please focus on one question per post (but feel free to create multiple posts) – Jonathan Hall Nov 07 '19 at 17:26
  • 1
    For the second question in the title, Python comes with a `timeit` module that can be used to do simple timings. – Carcigenicate Nov 07 '19 at 17:27
  • 1
    Perhaps you should start with making your program correct, not faster. Your `f` function doesn't do what it should. – kyrill Nov 07 '19 at 17:34
  • @kyril second r is always bigger than l. I have been testing the `F` function. for 20 minutes. can you tell me where `F` fails? Because it is supposed to find sum of all natural numbers from l to r(including l and r) Thank you for your Help – D-thec- tieve Nov 08 '19 at 03:35
  • According to the formula in the picture, `f` should compute `sum(lst[i] for i in range(l, r+1))`, where `lst` is the list (not set) of input numbers. – kyrill Nov 08 '19 at 11:25

0 Answers0