В то время как обещания и обратные вызовы хорошо работают во многих ситуациях, боль в задней части выражает нечто вроде:
if (!name) {
name = async1();
}
async2(name);
. В итоге вы пройдете через async1
; проверьте, не определено ли name
или нет, и соответственно вызовите обратный вызов.
async1(name, callback) {
if (name)
callback(name)
else {
doSomething(callback)
}
}
async1(name, async2)
Хотя в в порядке хорошо , это раздражает, когда у вас много подобных случаев и обработка ошибок.
Fibers
помогает в решении проблемы.
var Fiber = require('fibers')
function async1(container) {
var current = Fiber.current
var result
doSomething(function(name) {
result = name
fiber.run()
})
Fiber.yield()
return result
}
Fiber(function() {
var name
if (!name) {
name = async1()
}
async2(name)
// Make any number of async calls from here
}
Вы можете проверить проект здесь .
Рекурсивный подход:
# V is the target value, t is the tolerance
# A is the list of values
# B is the subset of A that is still below V-t
def combination_in_range(V, t, A, B=[]):
for i,a in enumerate(A):
if a > V+t: # B+[a] is too large
continue
# B+[a] can still be a possible list
B.append(a)
if a >= V-t: # Found a set that works
print B
# recursively try with a reduced V
# and a shortened list A
combination_in_range(V-a, t, A[i+1:], B)
B.pop() # drop [a] from possible list
A=[0.4, 2, 3, 1.4, 2.6, 6.3]
combination_in_range(5, 0.5, A)
Взгляните на itertools.combinations
def first_attempt(A=A):
for i in xrange(1,len(A)+1):
print [comb
for comb in list(itertools.combinations(A,i))
if 4.5 < sum(map(float, comb)) < 5.5
]
## -- End pasted text --
In [1861]: %timeit first_attempt
10000000 loops, best of 3: 29.4 ns per loop
Выход -
In [1890]: first_attempt(A=A)
[]
[(2, 3), (2, 2.6)]
[(0.4, 2, 3), (0.4, 2, 2.6), (0.4, 3, 1.4)]
[]
[]
[]