Last active
December 17, 2015 12:42
-
-
Save Paulius-Maruska/6c2c63dd478ada97481d to your computer and use it in GitHub Desktop.
combinations with python
This file contains hidden or 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 itertools import combinations | |
| SUM = 25 | |
| NUMS = [20, 17, 15, 13, 10, 8, 7, 5, 5] | |
| def calc(variant, nums): | |
| return sum([x for i, x in enumerate(nums) if i in variant]) | |
| def check(variant, sum, nums): | |
| return sum == calc(variant, nums) | |
| def header(nums, w): | |
| fmt = "%%%is" % w | |
| print(" ".join([fmt % x for x in nums])) | |
| def format(variant, nums, w): | |
| fmt = "%%%is" % w | |
| print(" ".join([fmt % ("x" if i in variant else " ") for i in range(len(nums))])) | |
| def check_combinations(sum, nums, w, found_callback): | |
| num = 0 | |
| for combination_length in range(1, len(nums) + 1): | |
| for comb in combinations(range(len(nums)), combination_length): | |
| if check(comb, sum, nums): | |
| found_callback(comb, nums, w) | |
| num += 1 | |
| return num | |
| def work(sum, nums, w=2): | |
| header(nums, w) | |
| total = check_combinations(sum, nums, w, format) | |
| print() | |
| print("Total combinations found: %i" % total) | |
| if __name__ == "__main__": | |
| work(SUM, NUMS, 4) |
This file contains hidden or 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
| $ python main.py | |
| 20 17 15 13 10 8 7 5 5 | |
| x x | |
| x x | |
| x x | |
| x x | |
| x x x | |
| x x x | |
| x x x | |
| x x x | |
| x x x x | |
| Total combinations found: 9 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
would run slightly faster if using generators instead of list comph.