全排列与子集-python实现-高级算法设计与分析-递归与分治章节

全排列

话不多说,直接上代码

x=[1,2,3]
def get_pailie(x,res):
    if len(x)==0:
        print(res)
        return 
    for i,item in enumerate(x):
        get_pailie(x[0:i]+x[i+1:],res+[item])

在这里插入图片描述

全子集

#全子集
x=[1,2,3]
def get_ziji(x):
    res=[[]]
    for i in x:
        res.extend([ item+[i] for item in res])
    return res

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
粗糙集理论是一种用于处理不确定性和不完备性信息的方法,其中属性约简算法是其重要应用之一。属性约简算法的目的是从原始数据集中提取出最具有代表性的属性子集,使得这些属性能够准确地描述数据集的特征。下面是一个基于Python的粗糙集属性约简算法实现: 1. 导入必要的库 ```python import numpy as np ``` 2. 定义一个函数来计算决策属性的正域和反域 ```python def get_pos_neg_region(decision_attr, dataset): pos_region = set() neg_region = set() for i in range(dataset.shape[0]): if dataset[i][-1] == decision_attr: pos_region.add(i) else: neg_region.add(i) return pos_region, neg_region ``` 3. 定义一个函数来计算属性的重要度 ```python def get_attr_importance(attr_idx, decision_attr, dataset): pos_region, neg_region = get_pos_neg_region(decision_attr, dataset) pos_cnt = len(pos_region) neg_cnt = len(neg_region) attr_values = set(dataset[:, attr_idx]) attr_cnt = len(attr_values) importance = 0 for attr_value in attr_values: attr_value_pos_region = set() attr_value_neg_region = set() for i in range(dataset.shape[0]): if dataset[i][attr_idx] == attr_value: if i in pos_region: attr_value_pos_region.add(i) else: attr_value_neg_region.add(i) attr_value_pos_cnt = len(attr_value_pos_region) attr_value_neg_cnt = len(attr_value_neg_region) if attr_value_pos_cnt == 0 or attr_value_neg_cnt == 0: continue p = attr_value_pos_cnt / pos_cnt q = attr_value_neg_cnt / neg_cnt importance += abs(p - q) / attr_cnt return importance ``` 4. 定义一个函数来进行属性约简 ```python def attribute_reduction(decision_attr, dataset): attr_cnt = dataset.shape[1] - 1 attrs = set(range(attr_cnt)) while True: max_importance = 0 max_importance_attr = None for attr in attrs: importance = get_attr_importance(attr, decision_attr, dataset) if importance > max_importance: max_importance = importance max_importance_attr = attr if max_importance == 0: break attrs.remove(max_importance_attr) return attrs ``` 5. 使用示例 ```python dataset = np.array([ [1, 0, 1, "yes"], [1, 1, 0, "yes"], [0, 1, 1, "no"], [1, 0, 0, "no"], [0, 1, 0, "no"] ]) decision_attr = "yes" attr_subset = attribute_reduction(decision_attr, dataset) print(attr_subset) ``` 输出结果为 `{1, 2}`,表示第2个和第3个属性是最具代表性的属性子集

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值