Dictionaries and Hashmaps: Count Triplets

59 篇文章 0 订阅
27 篇文章 0 订阅
#!/bin/python3
'''
import math
import os
import random
import re
import sys

# Complete the countTriplets function below.
#naive way
def countTriplets0(arr, r):
    s=sorted(arr)
    count=0
    n=len(arr)
    for i in range(n-2):
        for j in range(i+1,n-1):
            for k in range(j+1,n):
                if s[k]/s[j]==s[j]/s[i]==r:
                    count+=1
    return count

#more efficient way
from collections import defaultdict


def countTriplets(arr, r):
    count=0
    zd=defaultdict(int)
    for s in arr:
        zd[s]+=1
    keys=sorted(list(zd.keys()))
    n=len(keys)

    if r==1:
        for key,value in zd.items():
            if value>=3:
                count+=value*(value-1)*(value-2)/6
    else:
        if n>=3:
            for i in range(n-2):
                for j in range(i+1,n-1):
                    for k in range(j+1,n):
                        if keys[k]/keys[j]==keys[j]/keys[i]==r:
                            count+=zd[keys[k]]*zd[keys[j]]*zd[keys[i]]

    return int(count)


if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    nr = input().rstrip().split()

    n = int(nr[0])

    r = int(nr[1])

    arr = list(map(int, input().rstrip().split()))

    ans = countTriplets(arr, r)

    fptr.write(str(ans) + '\n')

    fptr.close()

'''
import math
import os
import random
import re
import sys
from collections import defaultdict

# Complete the countTriplets function below.
def countTriplets(arr, r):
    res = 0
    pairs = defaultdict(int)
    triplets = defaultdict(int)

    for el in arr:
        res += triplets[el]
        triplets[r*el] += pairs[el]
        pairs[r*el] += 1
        #print("el = {} triplets = {} pairs = {}".format(el, dict(triplets), dict(pairs)))

    return res

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    nr = input().rstrip().split()

    n = int(nr[0])

    r = int(nr[1])

    arr = list(map(int, input().rstrip().split()))

    ans = countTriplets(arr, r)

    fptr.write(str(ans) + '\n')

    fptr.close()
#'''

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值