Gautam Sagar
Gautam Sagar

Reputation: 63

My Code Doesn't work every time i run it

Given a sequence of non-negative integers a0,…,an−1, find the maximum pairwise product, that is, the largest integer that can be obtained by multiplying two different elements from the sequence (or, more formally, max0≤i≠j≤n−1aiaj). Different elements here mean ai and aj with i≠j (it can be the case that ai=aj).

Input format

The first line of the input contains an integer n. The next line contains n non-negative integers a0,…,an−1.

Constraints

2≤n≤2⋅105; 0≤a0,…,an−1≤105.

Output format

Output a single number — the maximum pairwise product.

This code works fine but sometimes when I run it it shows:

Traceback (most recent call last):
  File "C:\Users\gauta\AppData\Local\Programs\Python\Python35\gen.py", line 26, in <module>
    print(max(c))
ValueError: max() arg is an empty sequence

It shows This Only when Total elements in list 'a' are 2 or 3.

How can I improve this code and fix that problem, and will this code show a time limit exceeded or integer overflow bug?

import random  
import time  
b=time.time()  
a=list()  
c=list()   
n=random.randint(2,12)  
#appending random numbers in a list 'a'
g=1  
while(g<=n): 
   a.append(random.randint(0,10))  
   g=g+1  
print(a)  
print("Total elements in the list= %s"%len(a))  
#Appending Done
for i in range(2,n):
    for j in range (2,n):               
       if a[i]*a[j]>0:
           if a[i]!=a[j]:  
               m=a[i]*a[j]  
               c.append(m)   
           else:  
               continue  
      else:  
           continue  
print(max(c))  
time=time.time()-b  
print("%s"%(time.time()-b))  

Upvotes: 0

Views: 237

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121634

Your code has two flaws:

  • You run two loops with range(2, n), but n randomly can be set to 2. range(2, 2) is an empty sequence, so your loop body will not run and you end up with an empty list c

  • You mask the name time by assigning the result of the time.time() - b expression to it. Any further attempts to access time.time will give you an AttributeError as a floating point object has no such attribute. Rename that variable.

Next, you are using a O(N^2) approach; exponential growth in time used for every increase of the number of elements in a. This is certainly going to hit the time limits very quickly. All you need is to find the two largest integers in a and multiply those; this can be done in O(N) linear time. So if len(a) is 1000, your approach requires 1 million steps, while a linear time approach would only take 1000 steps.

The most efficient way to find K largest numbers in a sequence, is to use the heapq.nlargest() function, which finds those numbers in O(NlogK) time; for a fixed K=2, that makes this a O(N) linear time approach. You can use the operator.mul() function to multiply the two integers found:

import heapq
import operator

if len(a) > 1:
    result = operator.mul(*heapq.nlargest(2, a))
elif a:
    result = a[0]  # only one number, it's the largest
else:
    result = None  # no numbers, no result

Upvotes: 3

Rajan Chauhan
Rajan Chauhan

Reputation: 1375

It is not recommended to use variable name which are also the name of modules you are using

import random  
import time  
b=time.time()  
a=list()  
c=list()   
n=random.randint(2,12)  
#appending random numbers in a list 'a'
g=1  
while(g<=n):
    a.append(random.randint(0,10))
    g=g+1  
print(a)  
print("Total elements in the list= %s"%len(a))  
#Appending Done
for i in range(2,n):
    for j in range (2,n):
        if a[i]*a[j]>0:
            if a[i]!=a[j]:  
                m=a[i]*a[j]  
                c.append(m)   
            else:  
                continue  
        else:  
            continue  
print(max(c))  
othertime=time.time()-b
print(type(othertime)) #here in this line you changed the time to float     value hence now onwards you can't use time module as you were using before hence i renamed time variable to other.   
print("%s" %(time.time()-b))  

By changing variable name time to other time you can use time module again so remember this thing in future never to name variables with other modules name or keywords name otherwise their behavior will get lost in your code.

Upvotes: 1

Related Questions