Dataframe 1:
| 联系方式|幂值|
| --------------|--------------|
| 0| 1|
| 1|二|
| 二|四个|
| 三|八|
| 四个|十六岁|
| 五|三十二|
Dataframe 2:
| 组合值|
| --------------|
| 二十|
| 五十|
Stack Overflow上的某个人提供了以下R代码。
Finding all sum of 2 power value combination values of a given number in R
我在Python中寻找相同的代码。
toCodes <- function(x) {
n <- floor(log2(x))
pow <- rev(seq.int(max(n)))
# 'y' is the matrix of codes
y <- t(sapply(x, \(.x) (.x %/% 2^pow) %% 2L))
i_cols <- apply(y, 2, \(.y) any(.y != 0L))
colnames(y) <- sprintf("code_%d", 2^pow)
#
possiblecodes <- apply(y, 1, \(p) {
codes <- 2^pow[as.logical(p)]
paste(rev(codes), collapse = ",")
})
data.frame(combinedvalue = x, possiblecodes, y[, i_cols])
}
x <- c(20L, 50L)
toCodes(x)
1条答案
按热度按时间lc8prwob1#
调用to_codes的函数,该函数接受整数x的数组作为输入,并返回具有三列的pandas DataFrame:combinedvalue、possiblecodes和一组标为code_2^n的列,其中n是2的幂。