diff options
Diffstat (limited to 'challenge-248/packy-anderson/python')
| -rwxr-xr-x | challenge-248/packy-anderson/python/ch-1.py | 29 | ||||
| -rwxr-xr-x | challenge-248/packy-anderson/python/ch-2.py | 49 |
2 files changed, 78 insertions, 0 deletions
diff --git a/challenge-248/packy-anderson/python/ch-1.py b/challenge-248/packy-anderson/python/ch-1.py new file mode 100755 index 0000000000..e4f309808e --- /dev/null +++ b/challenge-248/packy-anderson/python/ch-1.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python + +def shortestDistance(s, c): + # split the string into an array of characters + strchar = list(s) + # find the positions of the target char + pos = [ x for x in range(len(s)) if strchar[x] == c ] + + output = [] + for i in range(len(s)): + # find the distances + distance = [ abs(i - p) for p in pos ] + # find the minimum distance + output.append( min(distance) ) + return output + +def comma_join(arr): + return ','.join(map(lambda i: str(i), arr)) + +def solution(s, c): + print(f'Input: $str = "{s}", $char = "{c}"') + output = shortestDistance(s, c) + print(f'Output: ({comma_join(output)})') + +print('Example 1:') +solution("loveleetcode", "e") + +print('\nExample 2:') +solution("aaab", "b")
\ No newline at end of file diff --git a/challenge-248/packy-anderson/python/ch-2.py b/challenge-248/packy-anderson/python/ch-2.py new file mode 100755 index 0000000000..a31b91af1a --- /dev/null +++ b/challenge-248/packy-anderson/python/ch-2.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python + +def submatrixSum(a): + # subtract 1 because we're 0-indexed + M = len(a) - 1 # rows + N = len(a[0]) - 1 # columns + # we are ASSUMING the matrix is consistent with + # each row having the same number of columns + b = [] + for i in range(M): + row = [] + for k in range(N): + row.append( a[i ][k] + a[i ][k+1] + + a[i+1][k] + a[i+1][k+1] ) + b.append(row) + return b + +def formatMatrix(matrix, indent=13): + output = [] + for row in matrix: + output_row = ' ' * indent + ' [' + output_row += ', '.join(map(lambda i: str(i), row)) + output_row += ']' + output.append(output_row) + + return( + "[\n" + ",\n".join(output) + "\n" + + ' ' * indent + ']' + ) + +def solution(a): + print(f'Input: $a = {formatMatrix(a)}') + b = submatrixSum(a) + print(f'Output: $b = {formatMatrix(b)}') + +print('Example 1:') +solution([ + [1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12] + ]) + +print('\nExample 2:') +solution([ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 1] + ]) |
