We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
passed 6/16 test cases. failed 10/16 due to timeout. finding a way to optimize it. any suggestion?
fromitertoolsimport*importmathn=int(input())a=list(map(int,input().split()))b=list(map(int,input().split()))n_a=[]n_b=[]sa=sum(a)sb=sum(b)flag=0foriinrange(n):n_a.append(list(range(1,a[i]+1)))"""make a list of all possible values of number of bad products for each product by A"""n_b.append(list(range(1,b[i]+1)))#sameforBforiinproduct(*n_a):"""iterate through all the possible combinations of number of bad product by A"""forjinproduct(*n_b):"""iterate through all the possible combinations of number of bad product by B"""count=0"""counting the number of times ratio is maintained for the current combination number of bad products by A and B """p=sum(i)*sb"""expression you will get by putting the given condition in a equation (A-overall/B-overall) spoilage ratio"""q=sum(j)*sam=math.gcd(p,q)"""reduce the fraction to its lowest terms"""p,q=p//m,q//m if(p/q)<=1:"""less than 1 then continue to next iteration"""continueforkinrange(n):"""each pair of kth product check the equality of ratio """r=(j[k]*a[k])s=(i[k]*b[k])"""expression you will get by putting the given condition in a equation (B-kth/A-kth) per product spoilage ratio"""t=math.gcd(r,s)"""reduce the fraction to its lowest terms"""r,s=r//t,s//tifr!=pors!=q:"""not equal then break the loop and go for next combination of i and j (change j)"""breakelse:count+=1"""equal then increase count"""ifcount==n:"""the ratio is same for all the n products then print the ratio and exit all the loops"""flag=1print("{}/{}".format(r,s))breakifflag==1:breakifflag==1:break
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Project Euler #236: Luxury Hampers
You are viewing a single comment's thread. Return to all comments →
passed 6/16 test cases. failed 10/16 due to timeout. finding a way to optimize it. any suggestion?