From eaad15f95557cf797ea0d02fad9eb7120eb63e2c Mon Sep 17 00:00:00 2001 From: Packy Anderson Date: Wed, 28 Feb 2024 00:55:49 -0500 Subject: Challenge 258 solutions by Packy Anderson * Raku * Perl * Python 1 Blog post --- challenge-258/packy-anderson/python/ch-2.py | 34 +++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100755 challenge-258/packy-anderson/python/ch-2.py (limited to 'challenge-258/packy-anderson/python/ch-2.py') diff --git a/challenge-258/packy-anderson/python/ch-2.py b/challenge-258/packy-anderson/python/ch-2.py new file mode 100755 index 0000000000..b9bdce3bb0 --- /dev/null +++ b/challenge-258/packy-anderson/python/ch-2.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python + +from functools import cache + +@cache +def setBitCount(i): + count = 0 + bit = 1 + while (bit <= i): + if i & bit: count += 1 # count if we have this bit set + bit <<= 1 # shift bits left, ie 10 becomes 100 + return count + +def valueSum(k, ints): + sum = 0 + for i in range(len(ints)): + if setBitCount(i) == k: sum += ints[i] + return sum + +def comma_join(arr): + return ', '.join(map(lambda i: str(i), arr)) + +def solution(k, ints): + print(f'Input: @ints = ({comma_join(ints)}), $k = {k}') + print(f'Output: {valueSum(k, ints)}') + +print('Example 1:') +solution(1, [2, 5, 9, 11, 3]) + +print('\nExample 2:') +solution(2, [2, 5, 9, 11, 3]) + +print('\nExample 3:') +solution(0, [2, 5, 9, 11, 3]) -- cgit