Bài toán: cho danh sách, tính tổng các phần tử.
Cách 1: Vòng lặp for
total = 0
list1 = [11, 22, 33, 44, 55, 66]
for ele in range(0, len(list1)):
total = total + list1[ele]
print("Sum of all elements in given list: ", total)
Sum of all elements in given list: 231
Cách 2: Vòng lặp while
total = 0
ele = 0
list1 = [11, 22, 33, 44, 55, 66]
while ele < len(list1):
total = total + list1[ele]
ele += 1
print("Sum of all elements in given list: ", total)
Sum of all elements in given list: 231
Cách 3: Đệ quy
list1 = [11, 22, 33, 44, 55, 66]
def sumOfList(list, size):
if size == 0:
return 0
else:
return list[size - 1] + sumOfList(list, size - 1)
total = sumOfList(list1, len(list1))
print("Sum of all elements in given list: ", total)
Sum of all elements in given list: 231
Kết luận
Đã học 3 cách tính tổng list: for, while, đệ quy. Thực tế dùng sum(list) tích hợp nhanh nhất.