Functional Deliverance solution in Uncategorized category for Loading Cargo by rgbkrk
# migrated from python 2.7
from itertools import combinations,chain
Minimal possible weight difference between stone piles
Let's get funcy (bad pun... I know, terrible)
total_weight = sum_in_right + sum_in_left
diff_weight = abs(sum_in_right - sum_in_left)
Some quick algebra...
total_weight - sum_in_left - sum_in_left = sum_in_right - sum_in_left
diff_weight = abs(total_weight - 2*sum_in_left)
# Total_weight is used later to help compute differences
total_weight = sum(stones)
# Get all the possible combinations that can go in the left hand,
# noting that we only have to look at half of the total combinations
# (Reverse the roles of the right and left hand)
combo_gens = [combinations(stones,num_in_left_hand) for num_in_left_hand in range(len(stones)/2 +1)]
combos = chain(*combo_gens)
# Sum every possible left hand
sums_in_left = list(map(sum, combos))
# Compute the differences
diff_weights = [abs(total_weight-2*sum_in_left) for sum_in_left in sums_in_left]
if __name__ == '__main__':
assert checkio([10,10]) == 0, 'First, with equal weights'
assert checkio() == 10, 'Second, with a single stone'
assert checkio([5, 8, 13, 27, 14]) == 3, 'Third'
assert checkio([5,5,6,5]) == 1, 'Fourth'
assert checkio([12, 30, 30, 32, 42, 49]) == 9, 'Fifth'
print('All is ok')
Oct. 27, 2012