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

โปรแกรม Python สร้างคลาสหา Subsets ทั้งหมดจากชุดจำนวนเต็มที่ไม่ซ้ำ


เมื่อต้องการสร้างคลาสเพื่อหา Subsets ทั้งหมดของจำนวนเต็มจากลิสต์ ใช้วิธี Object-Oriented กำหนดคลาสและแอตทริบิวต์ กำหนดฟังก์ชันภายในคลาสที่ดำเนินการบางอย่าง สร้างอินสแตนซ์ของคลาส และใช้ฟังก์ชันดำเนินการ

ตัวอย่าง

class get_subset:
    def sort_list(self, my_list):
        return self.subset_find([], sorted(my_list))

    def subset_find(self, curr, my_list):
        if my_list:
            return self.subset_find(curr, my_list[1:]) + self.subset_find(curr + [my_list[0]], my_list[1:])
        return [curr]

my_list = []
num_elem = int(input("Enter the number of elements in the list.. "))
for i in range(0, num_elem):
    elem = int(input("Enter the element.."))
    my_list.append(elem)
print("Subsets of the list are : ")
print(get_subset().sort_list(my_list))

ผลลัพธ์

Enter the number of elements in the list.. 3
Enter the element.. 45
Enter the element.. 12
Enter the element.. 67
Subsets of the list are : [[], [67], [45], [45, 67], [12], [12, 67], [12, 45], [12, 45, 67]]

คำอธิบาย

  • กำหนดคลาส 'get_subset' มีฟังก์ชัน 'sort_list' และ 'subset_find'
  • ใช้ดำเนินการเรียงลิสต์ และหา Subsets ทั้งหมดจากข้อมูลลิสต์
  • สร้างอินสแตนซ์ของคลาสนี้
  • ป้อนข้อมูลลิสต์ และดำเนินการ
  • แสดงข้อความและเอาต์พุทที่เกี่ยวข้องบนคอนโซล