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

โปรแกรม Python นับจำนวนการเกิดขึ้นขององค์ประกอบในรายการที่เชื่อมโยงโดยไม่ต้องใช้การเรียกซ้ำ


เมื่อจำเป็นต้องนับจำนวนการเกิดขององค์ประกอบเฉพาะในรายการที่เชื่อมโยงโดยไม่ต้องใช้การเรียกซ้ำ วิธีการเพิ่มองค์ประกอบในรายการที่เชื่อมโยง วิธีการแสดงองค์ประกอบของรายการที่เชื่อมโยง และวิธีการนับการเกิดขึ้น ของค่าที่กำหนดไว้

ด้านล่างนี้เป็นการสาธิตสำหรับสิ่งเดียวกัน -

ตัวอย่าง

class Node:
   def __init__(self, data):
      self.data = data
      self.next = None

class my_linked_list:
   def __init__(self):
      self.head = None
      self.last_node = None

   def add_value(self, my_data):
      if self.last_node is None:
         self.head = Node(my_data)
         self.last_node = self.head
      else:
         self.last_node.next = Node(my_data)
         self.last_node = self.last_node.next

   def print_it(self):
      curr = self.head
      while curr:
         print(curr.data)
         curr = curr.next

   def count_val(self, key):
      curr = self.head
      my_count = 0
      while curr:
         if curr.data == key:
            my_count = my_count + 1
         curr = curr.next
      return my_count

my_instance = my_linked_list()
my_list = [56, 43, 70, 67, 89, 91, 70, 23, 46, 70]
for elem in my_list:
   my_instance.add_value(elem)
print("The linked list contains the below elements:")
my_instance.print_it()

key_val = int(input('Enter the data item: '))
count_val = my_instance.count_val(key_val)
print('{0} occurs {1} time(s) in the list.'.format(key_val, count_val))

ผลลัพธ์

The linked list contains the below elements:
56
43
70
67
89
91
70
23
46
70
Enter the data item: 70
70 occurs 3 time(s) in the list.

คำอธิบาย

  • สร้างคลาส "โหนด" แล้ว

  • สร้างคลาส "my_linked_list" อีกคลาสที่มีแอตทริบิวต์ที่จำเป็นแล้ว

  • มีฟังก์ชัน 'init' ที่ใช้ในการเริ่มต้นองค์ประกอบแรก นั่นคือ 'head' เป็น 'None' และโหนดสุดท้ายเป็น 'None'

  • มีการกำหนดวิธีการอื่นที่ชื่อว่า 'add_value' ซึ่งใช้ในการเพิ่มข้อมูลไปยังรายการที่เชื่อมโยง

  • มีการกำหนดวิธีการอื่นที่ชื่อว่า 'print_it' ซึ่งจะวนซ้ำในรายการ และพิมพ์องค์ประกอบ

  • มีการกำหนดวิธีการอื่นที่เรียกว่า 'count_val' ซึ่งใช้เพื่อค้นหาความถี่ของการเกิดองค์ประกอบเฉพาะในรายการที่เชื่อมโยง

  • วัตถุของคลาส 'my_linked_list' ถูกสร้างขึ้น

  • มีการเรียกเมธอด count_val เพื่อค้นหาความถี่ขององค์ประกอบเฉพาะ

  • เอาต์พุตนี้จะแสดงบนคอนโซล