Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรมหา Tuple ที่มีผลคูณเท่ากันใน Python

มีอาร์เรย์ nums ค่า unique บวก หาจำนวน tuple (a,b,c,d) ที่ a*b = c*d และ a,b,c,d ต่างกันทุกตัว

ตัวอย่าง: nums=[2,3,4,6] ผลลัพธ์ 8 (8 permutations ของคู่ (2,6) และ (3,4))

วิธีแก้ปัญหา

  1. นับความถี่ของผลคูณทุกคู่ dic[nums[i]*nums[j]]++
  2. สำหรับแต่ละความถี่ v:
    • จำนวนคู่ที่เลือกได้ 2 คู่จาก v คู่ = C(v,2)
    • แต่ละคู่จัดเรียงได้ 8 แบบ (2! × 2! × 2)
    • สูตร: ans += (v-1)/2 * (8+8*(v-1)) ≡ 8 * C(v,2)

ตัวอย่างโค้ด

from collections import defaultdict

def solve(nums):
    dic = defaultdict(int)
    ans = 0
    for i in range(len(nums)-1):
        for j in range(i+1, len(nums)):
            dic[nums[i]*nums[j]] += 1
    for v in dic.values():
        if v == 1: continue
        v = v - 1
        s = (v/2) * (8 + 8*v)
        ans += s
    return int(ans)

nums = [3,4,6,2]
print(solve(nums))

อินพุต

[3,4,6,2]

เอาต์พุต

8