为了账号安全,请及时绑定邮箱和手机立即绑定

如何从数组的元素中获取不同的组合?

如何从数组的元素中获取不同的组合?

慕姐8265434 2023-12-14 16:34:53
拿这个“str”“ABCDE”来说,它有以下"AB", "ABC", "ABCD","ABCDE","DE", "CDE", "BCDE", "CD","BC"关于顺序的组合。我试过//  thi is javascript code            const val = 'ABCDE'            let array = []            for (i = 0; i < val.length-1; i++) {                  array.push(val.slice(i,val.length))                  array.push(val.slice(0,i+2))                  array.push(val.slice(i,val.length-i))                  }                  console.log(                  array,                  array.includes('BC'),                  array.includes('CD')                  )// this is the reuslts: ["ABCDE", "AB", "ABCDE", "BCDE", "ABC", "BCD", "CDE", "ABCD", "C", "DE", "ABCDE", ""]//this reslutes don't have compnations like 'BC' or 'CD'我没有真正得到我需要的结果。您对 javascript 或 python 有什么想法吗?我认为 pythonpanda或可能NumPy库有这样的东西。
查看完整描述

2 回答

?
繁星coding

TA贡献1797条经验 获得超4个赞

您需要两个子字符串嵌套循环。


function getAllSubstrings(str) {

    const result = [];


    for (let i = 0; i < str.length - 1; i++) {

        for (let j = i + 2; j < str.length + 1; j++) {

            result.push(str.slice(i, j));

        }

    }

    return result;

}


console.log(getAllSubstrings('ABCDE'));

.as-console-wrapper { max-height: 100% !important; top: 0; }


查看完整回答
反对 回复 2023-12-14
?
慕哥6287543

TA贡献1831条经验 获得超10个赞

在Python中一切都很简单。


from itertools import combinations

val = 'ABCDE'

print([''.join(l) for i in range(len(x)) for l in combinations(x, i+1)])


查看完整回答
反对 回复 2023-12-14
  • 2 回答
  • 0 关注
  • 64 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信