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

โปรแกรมนับ Match ของคู่ (Base, Number) ใน Python

โจทย์

มีคู่ (Base, Number) หลายคู่ ต้องนับจำนวนคู่ที่แทนค่าเท่ากัน (เช่น 15 base 10 = 17 base 8) คู่อาจซ้ำหรือ Invalid ได้

ตัวอย่าง: [(10,15), (8,17)] → Output: 1 (15₁₀ = 17₈ = 15)

อัลกอริธึม

  1. แปลงแต่ละคู่เป็นค่า Integer: int(str(num), base)
  2. นับ Frequency ของแต่ละค่า
  3. แต่ละค่าที่มี Frequency = f ให้ Match = f×(f-1)/2

โค้ด Python


from collections import defaultdict

def solve(num_inputs, input_arr):
    temp_dict = defaultdict(int)
    for i in range(num_inputs):
        num_base, num_val = str(input_arr[i][0]), str(input_arr[i][1])
        temp_dict[int(num_val, int(num_base))] += 1
    cnt = 0
    for value in temp_dict.values():
        cnt += value * (value - 1) // 2
    return cnt

print(solve(2, [(10, 15), (8, 17)]))  # Output: 1

Input / Output

Input:  2, [(10, 15), (8, 17)]
Output: 1