# 解 Perl Weekly Challenge 083：以 Raku 與 Python。

Perl Weekly Challenge 083 這周也是兩個題目。這次試著用 Raku 與 Python 來解看看。

## TASK #1 › Words Length

``````# Raku
sub words-length (Str \$s) {
my @w = \$s.trim.indices(' ');
return @w.elems == 0 ?? 0 !! @w.tail - @w.head - @w.elems + 1;
}

# Python
def wordsLength(s):
s = s.strip(' ')
p = s.find(' ')
return 0 if p == -1 else (s.rfind(' ') - p - s.count(' ') + 1);``````

## TASK #2 › Flip Array

`@A` 衍生出長度為 `\$k` 的子集合 `@B`，這是取組合，`@A` 的長度若是 n，就是會有 C(n, k) 種取法。

``````# Raku
sub flip-elems (@n) {
my \$sum = [+] @n;
my @min_combination = @n;
my \$min_sum = Inf;
K: for 1..@n.elems - 1 -> \$k {
for @n.combinations(\$k) -> @c {
my \$s = \$sum - 2 * ([+] @c);
if 0 <= \$s < \$min_sum {
@min_combination = @c;
\$min_sum = \$s;
if \$s == 0 {
last K;
}
}
}
}
say ">> \$min_sum = ([+] {@n}) - 2 * ([+] {@min_combination})";
return @min_combination.elems;
}

# Python
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 = 0
minCombination = ()
for minSum, minCombination in flipCombination(A):
if minSum == 0:
break
print(f'>> {minSum} = sum({A}) - 2 * sum({minCombination})')
return len(minCombination)``````