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

ตรวจสอบว่าอาร์เรย์มีสมาชิกเท่ากับผลรวมของสมาชิกอื่นหรือไม่ ใน Python


ปัญหา

ให้อาร์เรย์ nums ตรวจสอบว่ามีสมาชิกตัวใดตัวหนึ่งที่มีค่าเท่ากับผลรวมของสมาชิกอื่นทั้งหมดหรือไม่

ตัวอย่าง

nums = [3,2,10,4,1] → 10 = 3+2+4+1 → True

แนวคิดการแก้ปัญหา

  1. คำนวณผลรวมทั้งหมด total
  2. ถ้า total เป็นเลขคู่ และมีสมาชิกเท่ากับ total/2 → True
  3. เพราะถ้า x = sum(others) → total = x + x = 2x → x = total/2

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

from collections import Counter

def solve(nums):
    total = sum(nums)
    if total % 2 != 0:
        return False
    target = total // 2
    freq = Counter(nums)
    return freq[target] > 0

print(solve([3, 2, 10, 4, 1]))  # True

อินพุต / เอาต์พุต

Input:  [3,2,10,4,1]
Output: True