Python程式:從一組不同的整數中建立類並獲取所有可能的子集


當需要建立一個類來獲取列表中所有可能的整數子集時,可以使用面向物件的方法。在此,定義一個類並定義屬性。在類中定義執行某些操作的函式。建立一個類的例項,並使用這些函式執行計算器操作。

下面是相同的演示 -

示例

 線上演示

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”等函式。
  • 這些用於執行諸如排序列表和分別從列表資料中獲取所有可能的子集之類的操作。
  • 建立此類的例項。
  • 輸入列表資料,並對其執行操作。
  • 在控制檯上顯示相關訊息和輸出。

更新於:2021年3月12日

576 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.