亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從數組的元素中獲取不同的組合?

如何從數組的元素中獲取不同的組合?

慕姐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 關注
  • 174 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號