Last active
December 29, 2016 13:01
-
-
Save ruslux/94bd91c1065a1e4b552f81008719a034 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from random import randint | |
def find_components(raw_array, value): | |
""" | |
~O(n) find first combination in `new_array` which sum equal `value`. | |
""" | |
# remove from array all values grand then needed value | |
array = list(filter(lambda x: x <= value, raw_array)) | |
# keep only unique values | |
array = list(set(array)) | |
# sort big to small | |
array = sorted(array, reverse=True) | |
for number in array: | |
if number == value: | |
return [number] | |
# remove number from array, because if does not exists combinations | |
# with him, then we don't need recombinate it in other cycle | |
array.remove(number) | |
# get remainder value | |
diff = value - number | |
# copy remainder array | |
_copy = list(array) | |
# find in remainder array other summ components for that number | |
sub_components = find_components(_copy, diff) | |
if sub_components: | |
return [number] + sub_components | |
return [] | |
arr = map(lambda x: randint(1, 10000), range(0, 1000)) | |
need = randint(1, 20000) | |
need_combinations = find_components(list(arr), need) | |
if need_combinations: | |
msg = "for number {} founded combination {} with summ {}" | |
print(msg.format(need, need_combinations, sum(need_combinations))) | |
else: | |
print("does not have combinations") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment