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”等函数。
- 这些用于执行诸如排序列表和分别从列表数据中获取所有可能的子集之类的操作。
- 创建此类的实例。
- 输入列表数据,并对其执行操作。
- 在控制台上显示相关消息和输出。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP