求与给定R代码功能一致的Python实现:数字分解为2的幂组合
Python实现:找出给定数字的2的幂值组合和
以下是与指定R代码功能完全一致的Python实现,可将给定数字分解为2的幂值的组合,并生成包含组合值、幂值组合字符串及对应二进制位的DataFrame:
import math import pandas as pd def to_codes(x): # 计算每个数字的log2向下取整值,取最大值确定需要覆盖的2的幂范围 n_list = [math.floor(math.log2(num)) for num in x] max_n = max(n_list) # 生成从max_n到1的整数序列,对应2的幂的指数 pow_seq = list(range(max_n, 0, -1)) powers = [2**p for p in pow_seq] # 生成每个数字对应的二进制位矩阵 binary_matrix = [] for num in x: bits = [(num // power) % 2 for power in powers] binary_matrix.append(bits) # 转换为DataFrame并设置列名 df_binary = pd.DataFrame(binary_matrix, columns=[f"code_{p}" for p in powers]) # 筛选出至少有一个非0值的列 valid_cols = df_binary.columns[df_binary.any(axis=0)] df_binary = df_binary[valid_cols] # 生成每个数字对应的幂值组合字符串 possible_codes = [] for idx in range(len(x)): row_bits = df_binary.iloc[idx].values # 提取当前数字用到的2的幂值 used_powers = [int(col.split("_")[1]) for col, bit in zip(df_binary.columns, row_bits) if bit == 1] # 反转后用逗号连接 possible_codes.append(",".join(map(str, reversed(used_powers)))) # 构造最终结果DataFrame result = pd.DataFrame({ "combinedvalue": x, "possiblecodes": possible_codes }) result = pd.concat([result, df_binary], axis=1) return result # 测试示例 x = [20, 50] print(to_codes(x))
输出结果
combinedvalue possiblecodes code_32 code_16 code_4 code_2 0 20 4,16 0 1 1 0 1 50 2,16,32 1 1 0 1
内容的提问来源于stack exchange,提问作者Rajesh Addunuri
相关产品推荐
相关产品推荐

