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

การหาผลรวมสมาชิกสลับกัน (Alternate Summation) ในลิสต์ Python

ให้ลิสต์ตัวเลข ต้องการหาผลรวมของสมาชิกสลับกัน (Alternate elements) คือ ผลรวมตำแหน่งคู่ และผลรวมตำแหน่งคี่

วิธีที่ 1: ใช้ List Slicing

Slice ลิสต์เป็น 2 ชุด: ตำแหน่งคู่ (0, 2, 4...) และ ตำแหน่งคี่ (1, 3, 5...) แล้ว sum แต่ละชุด

ตัวอย่าง

listA = [13, 65, 78, 13, 12, 13, 65]
print("Given list:", listA)

res = [sum(listA[i::2]) for i in range(len(listA) // (len(listA) // 2))]
print("Sum of alternate elements in the list:\n", res)

ผลลัพธ์

Given list: [13, 65, 78, 13, 12, 13, 65]
Sum of alternate elements in the list: [168, 91]

คำอธิบาย: ตำแหน่งคู่ (0,2,4,6) = 13+78+12+65 = 168, ตำแหน่งคี่ (1,3,5) = 65+13+13 = 91

วิธีที่ 2: ใช้ range และ modulo (% 2)

วนลูปตรวจสอบดัชนีคู่/คี่ สะสมผลรวมแยกกัน

ตัวอย่าง

listA = [13, 65, 78, 13, 12, 13, 65]
print("Given list:", listA)

res = [0, 0]
for i in range(len(listA)):
    if i % 2:
        res[1] += listA[i]  # index คี่
    else:
        res[0] += listA[i]  # index คู่

print("Sum of alternate elements in the list:\n", res)

ผลลัพธ์

Given list: [13, 65, 78, 13, 12, 13, 65]
Sum of alternate elements in the list: [168, 91]

วิธีที่ 3 (Pythonic): ใช้ slicing ตรงๆ

even_sum = sum(listA[::2])   # index 0,2,4...
odd_sum = sum(listA[1::2])   # index 1,3,5...
print([even_sum, odd_sum])