ในบทความนี้ เราจะเรียนรู้เกี่ยวกับวิธีแก้ปัญหาตามที่ระบุด้านล่าง
แจ้งปัญหา − เราได้รับรายการที่ทำซ้ำได้ เราต้องนับจำนวนบวกและลบในนั้นและแสดงผล
แนวทางที่ 1 - แนวทางแบบ Brute-force โดยใช้โครงสร้างแบบวนซ้ำ (สำหรับ)
ที่นี่เราต้องวนซ้ำแต่ละองค์ประกอบในรายการโดยใช้ 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 being 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 โดยใช้โครงสร้างการวนซ้ำ (ในขณะที่)
ที่นี่เราต้องวนซ้ำแต่ละองค์ประกอบในรายการโดยใช้ for วนซ้ำและตรวจสอบว่า 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
เราใช้ความช่วยเหลือจากนิพจน์ตัวกรองและแลมบ์ดา ซึ่งเราสามารถแยกความแตกต่างระหว่างจำนวนบวกและค่าลบได้โดยตรง
ตัวอย่าง
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
ตัวแปรทั้งหมดได้รับการประกาศในขอบเขตท้องถิ่นและการอ้างอิงของตัวแปรนั้นดูได้จากรูปด้านบน
บทสรุป
ในบทความนี้ เราได้เรียนรู้วิธีนับจำนวนบวกและลบในรายการ