我已经看到了几个关于如何在数组中生成所有可能的元素组合的类似问题.但是我很难弄清楚如何编写一个只输出组合对的算法.任何建议都将超级赞赏!
从以下数组开始(带有N个元素):
var array = ["apple", "banana", "lemon", "mango"];
Run Code Online (Sandbox Code Playgroud)
得到以下结果:
var result = [
"apple banana"
"apple lemon"
"apple mango"
"banana lemon"
"banana mango"
"lemon mango"
];
Run Code Online (Sandbox Code Playgroud)
我正在尝试以下方法,但这导致所有可能的组合,而不是组合对.
var letters = splSentences;
var combi = [];
var temp= "";
var letLen = Math.pow(2, letters.length);
for (var i = 0; i < letLen ; i++){
temp= "";
for (var j=0;j<letters.length;j++) {
if ((i & Math.pow(2,j))){
temp += letters[j]+ " "
}
}
if (temp !== "") {
combi.push(temp);
} …Run Code Online (Sandbox Code Playgroud) 我对python比较陌生,所以我甚至不确定我是否以正确的方式接近它.但我在任何地方都找不到好的解决方案.
为了避免非常丑陋和重复的代码,我想循环if语句的elif部分.
这是我想修复的丑陋代码:
def codeToChar(code):
chars = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm"
if code == ord(chars[0]): ##### SUPER UGLY
return chars[0]
elif code == ord(chars[1]):
return chars[1]
elif code == ord(chars[2]):
return chars[2]
elif code == ord(chars[3]):
return chars[3]
elif code == ord(chars[4]):
return chars[4]
elif code == ord(chars[5]):
return chars[5]
..... etc .....
else:
return "wat"
Run Code Online (Sandbox Code Playgroud)
如您所见,索引递增1,所以我认为循环将非常简单.但是,当我尝试以下操作时,它不起作用,因为这必须被表述为if,elif,elif,else语句,而不是很多if语句.
我失败的尝试:
for x in xrange(0,len(chars)-1):
if code == ord(chars[x]):
return chars[x]
else:
return "wat"
Run Code Online (Sandbox Code Playgroud)
我该如何循环呢?注意:如果它有任何相关性,我使用curses模块对其进行编码,为项目构建键盘接口.非常感谢
我正在努力想出一个正则表达式来查找任何用方括号括起来的字符串。\n我从维基百科上抓取了一份大量文档,其中包含许多这样的段落:
\n\n"Theology translates into English from the Greek theologia (\xce\xb8\xce\xb5\xce\xbf\xce\xbb\xce\xbf\xce\xb3\xce\xaf\xce\xb1) which derived from \xce\xa4heos (\xce\x98\xce\xb5\xcf\x8c\xcf\x82), meaning "God," and -logia (-\xce\xbb\xce\xbf\xce\xb3\xce\xaf\xce\xb1),**[12]** meaning "utterances, sayings, or oracles" (a word related to logos **[\xce\xbb\xcf\x8c\xce\xb3\xce\xbf\xcf\x82][Citation needed]**".\nRun Code Online (Sandbox Code Playgroud)\n\n期望的结果是:
\n\n"Theology translates into English from the Greek theologia (\xce\xb8\xce\xb5\xce\xbf\xce\xbb\xce\xbf\xce\xb3\xce\xaf\xce\xb1) which derived from \xce\xa4heos (\xce\x98\xce\xb5\xcf\x8c\xcf\x82), meaning "God," and -logia (-\xce\xbb\xce\xbf\xce\xb3\xce\xaf\xce\xb1), meaning "utterances, sayings, or oracles" (a word related to logos".\nRun Code Online (Sandbox Code Playgroud)\n\n如有任何建议,我们将不胜感激。\n谢谢!
\nalgorithm ×1
arrays ×1
combinations ×1
for-loop ×1
if-statement ×1
javascript ×1
loops ×1
python ×1
regex ×1