ในบทความนี้ เราจะเรียนรู้วิธีแก้ปัญหาตามข้อกำหนดด้านล่าง
ข้อกำหนดปัญหา − เราได้รับลิสต์ iterable ต้องนับจำนวนบวกและลบในมันและแสดงผล
วิธีที่ 1 − Brute-force ใช้ลูป for
ที่นี่เราต้องวนแต่ละสมาชิกในลิสต์ด้วยลูป for และตรวจสอบว่า num >= 0 เพื่อกรองจำนวนบวก ถ้าเงื่อนไขเป็นจริง เพิ่ม pos_count มิฉะนั้นเพิ่ม neg_count
ตัวอย่าง
list1 = [1, -2, -4, 6, 7, -23, 45, -0]
pos_count, neg_count = 0, 0
# enhanced for loop
for num in list1:
# check for positive
if num >= 0:
pos_count += 1
else:
neg_count += 1
print("Positive numbers in the list:", pos_count)
print("Negative numbers in the list:", neg_count)
ผลลัพธ์
Positive numbers in the list: 5 Negative numbers in the list: 3
วิธีที่ 2 − Brute-force ใช้ลูป while
ที่นี่เราต้องวนแต่ละสมาชิกในลิสต์ด้วยลูป while และตรวจสอบว่า num >= 0 เพื่อกรองจำนวนบวก ถ้าเงื่อนไขเป็นจริง เพิ่ม pos_count มิฉะนั้นเพิ่ม neg_count
ตัวอย่าง
list1 = [1, -2, -4, 6, 7, -23, 45, -0]
pos_count, neg_count = 0, 0
num = 0
# while loop
while num < len(list1):
# check
if list1[num] >= 0:
pos_count += 1
else:
neg_count += 1
# increment num
num += 1
print("Positive numbers in the list:", pos_count)
print("Negative numbers in the list:", neg_count)
ผลลัพธ์
Positive numbers in the list: 5 Negative numbers in the list: 3
วิธีที่ 3 − ใช้ Python Lambda Expressions
ที่นี่เราช่วยเหลือของ filter และ lambda expressions เราสามารถแยกแยะระหว่างจำนวนบวกและลบได้โดยตรง
ตัวอย่าง
list1 = [1, -2, -4, 6, 7, -23, 45, -0]
neg_count = len(list(filter(lambda x: (x < 0), list1)))
pos_count = len(list(filter(lambda x: (x >= 0), list1)))
print("Positive numbers in the list:", pos_count)
print("Negative numbers in the list:", neg_count)
ผลลัพธ์
Positive numbers in the list: 5 Negative numbers in the list: 3
ตัวแปรทั้งหมดประกาศในขอบเขตท้องถิ่นและอ้างอิงของพวกเขาเห็นในรูปด้านบน
สรุป
ในบทความนี้ เราได้เรียนรู้ 3 วิธีนับจำนวนบวกและลบในลิสต์: for loop, while loop, และ filter+lambda