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

โปรแกรม Python หาองค์ประกอบที่เกิดจำนวนครั้งคี่ใน List


ภาพรวม

เมื่อต้องการหาองค์ประกอบที่เกิดจำนวนครั้งคี่ใน List สามารถนิยามเมธอด วนลูปผ่าน List ตรวจสอบว่าองค์ประกอบใน Nested Loop ตรงกันหรือไม่ ถ้าตรงเพิ่มตัวนับ หากตัวนับไม่หาร 2 ลงตัว คืนค่าองค์ประกอบนั้น มิฉะนั้นคืน -1

ตัวอย่างโค้ด

def odd_occurence(my_list, list_size):
    for i in range(0, list_size):
        count = 0
        for j in range(0, list_size):
            if my_list[i] == my_list[j]:
                count += 1
        if (count % 2 != 0):
            return my_list[i]
    return -1

my_list = [34, 56, 78, 99, 23, 34, 34, 56, 78, 99, 99, 99, 99, 34, 34, 56, 56]
print("The list is :")
print(my_list)
n = len(my_list)
print("The length is :")
print(n)
print("The method to find the element that occurs odd number of times is called ")
print("The element that occurs odd number of times is :")
print(odd_occurence(my_list, n))

ผลลัพธ์ตัวอย่าง

The list is : [34, 56, 78, 99, 23, 34, 34, 56, 78, 99, 99, 99, 99, 34, 34, 56, 56]
The length is : 17
The method to find the element that occurs odd number of times is called
The element that occurs odd number of times is : 34

คำอธิบาย

  • นิยามเมธอด odd_occurence รับ List และขนาดเป็นพารามิเตอร์
  • ใช้ขนาด List เป็น Range วนลูป List
  • วนลูปซ้อน 2 ชั้น ถ้าองค์ประกอบตรงกัน เพิ่มตัวแปร count
  • ถ้า count เป็นคี่ คืนค่าองค์ประกอบนั้น
  • นิยาม List จำนวนเต็ม แสดงบนคอนโซล
  • เก็บความยาว List ในตัวแปร
  • เรียกเมธอดส่งพารามิเตอร์ที่เกี่ยวข้อง
  • แสดงผลลัพธ์บนคอนโซล