diff options
| author | Kang-min Liu <gugod@gugod.org> | 2020-10-20 10:43:59 +0900 |
|---|---|---|
| committer | Kang-min Liu <gugod@gugod.org> | 2020-10-20 10:43:59 +0900 |
| commit | 000e17bf6effec267a6e848f77889acb06a65abe (patch) | |
| tree | f50af92b1713e1420f638e4746748cabe6b8f38b | |
| parent | 209b1176d61c80d704dd47821e16907040356bed (diff) | |
| download | perlweeklychallenge-club-000e17bf6effec267a6e848f77889acb06a65abe.tar.gz perlweeklychallenge-club-000e17bf6effec267a6e848f77889acb06a65abe.tar.bz2 perlweeklychallenge-club-000e17bf6effec267a6e848f77889acb06a65abe.zip | |
a solution of 083.2 in python3
| -rw-r--r-- | challenge-083/gugod/python/ch-2.py | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/challenge-083/gugod/python/ch-2.py b/challenge-083/gugod/python/ch-2.py new file mode 100644 index 0000000000..1a3a3bffc2 --- /dev/null +++ b/challenge-083/gugod/python/ch-2.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +import sys +import itertools + +def flipCombination(A): + minSum = nSum = sum(A) + minCombination = () + for k in range(1, len(A)): + for c in itertools.combinations(A, k): + s = nSum - 2 * sum(c) + if 0 <= s < minSum: + minCombination = c + minSum = s + yield minSum, minCombination + + +def flipElems(A): + minSum = sum(A) + minCombination = () + for s, c in flipCombination(A): + if s < minSum: + minSum = s + minCombination = c + if s == 0: + break + print(f'>> {minSum} = sum({A}) - 2 * sum({minCombination})') + return len(minCombination) + +# print(flipElems([2,13,10,8])) # 2 +# print(flipElems([10,12,2])) # 1 +print(flipElems(list(map(int, sys.argv[1:])))) |
