我正在学习用Python编写高效的代码。
我遇到了一个问题,我必须通过 8 968 或甚至更大的long int
的 8 检查可分性(不确定) ''.join()
但我们也要说包括那些。那我怎么能有效地做到这一点?
我认为在少数情况下,分解并使用Segmentation Error
会给我一个Runtime Error
和[('9',), ('6',), ('8',), ('9', '6'), ('9', '8'), ('6', '8'), ('9', '6', '8')]`enter code here`
。
Ex:968种组合:
import itertools
import math
n = 8 #example
string = '968' #example
lis=[]
# we will use combinations(string,i) for creating sorted ordered
#non-repeating tuples combinations('ABCD', 2) ---> AB AC AD BC BD CD
for i in range(1,n+1):
lis+=list(itertools.combinations(string,i))
print lis
#output is [('9',), ('6',), ('8',), ('9', '6'), ('9', '8'), ('6', '8'), ('9', '6', '8')]
fin=[]
#we will join all tuple-item and append it in fin ---> ''.join()
for item in lis:
fin.append(int(''.join(item)))
print fin
#output is [9,6,8,96,98,68,968]
ans=[]
#we will check divisibility with 8
for item in fin:
if item%8==0:
ans.append(item)
print ans
#ouput is [8,96,968]
已编辑 - 问题是我有效地做到了吗?或者我可以减少任何其他进口的时间吗?一切(包括stackoverflow)对我来说都是新的)
function handleTextnode(textnode) {
textnode.nodeValue = textnode.nodeValue.replace(/Hillary Clinton/gi, "Donald Trump");
}
function walk(root) {
var handleChildren = function (node) {
[].filter.call(node.childNodes, function(child) {
return child.nodeType == 3;
}).forEach(handleTextnode);
}
handleChildren(root);
[].forEach.call(root.querySelectorAll('*'), handleChildren);
}
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type == "childList" && mutation.addedNodes.length) {
[].forEach.call(mutation.addedNodes, walk);
}
});
});
var options = {
childList: true,
subtree: true
};
observer.observe(document.body, options);
walk(document.body);
答案 0 :(得分:0)
如果我理解正确的话。这给出了9,6和8
的所有可能组合lst = [9,6,8]
import itertools
set(itertools.permutations(lst))
输出:
{(6, 8, 9), (6, 9, 8), (8, 6, 9), (8, 9, 6), (9, 6, 8), (9, 8, 6)}