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

โปรแกรม Python หาผลรวมของสมาชิกในลิสต์

โจทย์: กำหนดลิสต์ หาผลรวมของสมาชิกทั้งหมด มี 2 วิธี

วิธี 1: ใช้ฟังก์ชัน built-in sum()

arr = [1, 2, 3, 4, 5]
ans = sum(arr)
print('Sum of the array is', ans)

ผลลัพธ์

15

โปรแกรม Python หาผลรวมของสมาชิกในลิสต์

วิธี 2: Brute-force (วนลูปบวกเอง)

total = 0
list1 = [1, 2, 3, 4, 5]
for ele in range(0, len(list1)):
    total = total + list1[ele]
print("Sum of all elements in given list:", total)

ผลลัพธ์

15

โปรแกรม Python หาผลรวมของสมาชิกในลิสต์

สรุป

เรียนรู้ 2 วิธีหาผลรวมลิสต์: sum() built-in และ brute-force loop