Link to count triplets problem
在下面的代码中,hackerrank网站说答案是错误的,但是当我在本地机器上运行代码时。具体来说,测试用例2是一个1001的数组,有一个1的三元组乘法器,预期输出应该是161700,在我的本地机器上我得到161700,但是在hackerrank网站上我得到它是不正确的。
def countTriplets(arr, r):
sum_array=[]
if int(r)==1:
for x in range(len(arr)-1):
sum_array.append((x*(x+1))/2)
return sum(sum_array)
else:
exp_dict={}
tripletCount=0
for x in arr:
if x in exp_dict:
exp_dict[x]+=1
else:
exp_dict[x]=1
for y in exp_dict:
#print(y)
if ((y % r ==0) or (y==1)) and ((y*r in exp_dict) and (y*r*r in exp_dict)):
#print((exp_dict[y]*exp_dict[y*r]*exp_dict[y*r*r]))
tripletCount+=(exp_dict[y]*exp_dict[y*r]*exp_dict[y*r*r])
#print("hello I am a computer nerd")
return tripletCount
最佳答案
要通过在线编码挑战,您的输出格式必须与预期格式匹配。你的程序正在生成161700.0
,预期的答案是161700
。这是因为分裂我将返回值转换为int
并且它通过了case。
def countTriplets(arr, r):
sum_array=[]
if int(r)==1:
for x in range(len(arr)-1):
sum_array.append((x*(x+1))/2)
return int(sum(sum_array)) # change in this line
else:
exp_dict={}
tripletCount=0
for x in arr:
if x in exp_dict:
exp_dict[x]+=1
else:
exp_dict[x]=1
for y in exp_dict:
#print(y)
if ((y % r ==0) or (y==1)) and ((y*r in exp_dict) and (y*r*r in exp_dict)):
#print((exp_dict[y]*exp_dict[y*r]*exp_dict[y*r*r]))
tripletCount+=(exp_dict[y]*exp_dict[y*r]*exp_dict[y*r*r])
#print("hello I am a computer nerd")
return tripletCount
然而,它仍然不能解决100%的测试用例这个答案是针对您所要求的测试用例的。