|
| 1 | +"""Kata - Reducing by steps |
| 2 | +
|
| 3 | +completed at: 2024-04-17 14:33:38 |
| 4 | +by: Jakub Červinka |
| 5 | +
|
| 6 | +Data: an array of integers, a function f of two variables and an init value. |
| 7 | +
|
| 8 | +`Example: a = [2, 4, 6, 8, 10, 20], f(x, y) = x + y; init = 0` |
| 9 | +
|
| 10 | +Output: an array of integers, say r, such that |
| 11 | +
|
| 12 | +`r = [r[0] = f(init, a[0]), r[1] = f(r[0], a[1]), r[2] = f(r[1], a[2]), ...]` |
| 13 | +
|
| 14 | +With our example: `r = [2, 6, 12, 20, 30, 50]` |
| 15 | +
|
| 16 | +#### Task: |
| 17 | +Write the following functions of two variables |
| 18 | +
|
| 19 | +- som : (x, y) -> x + y |
| 20 | +- mini : (x, y) -> min(x, y) |
| 21 | +- maxi : (x, y) -> max(x, y) |
| 22 | +- lcmu : (x, y) -> lcm(abs(x), abs(y) (see note for lcm) |
| 23 | +- gcdi : (x, y) -> gcd(abs(x), abs(y) (see note for gcd) |
| 24 | +
|
| 25 | +and |
| 26 | +
|
| 27 | +- function `oper_array(fct, arr, init)` (or operArray or oper-array) where |
| 28 | +
|
| 29 | + - `fct` is the function of two variables to apply to the array `arr` |
| 30 | +(fct will be one of `som, mini, maxi, lcmu or gcdi`) |
| 31 | + - `init` is the initial value |
| 32 | +
|
| 33 | +#### Examples: |
| 34 | +
|
| 35 | +``` |
| 36 | +a = [18, 69, -90, -78, 65, 40] |
| 37 | +oper_array(gcd, a, a[0]) => [18, 3, 3, 3, 1, 1] |
| 38 | +oper_array(lcm, a, a[0]) => [18, 414, 2070, 26910, 26910, 107640] |
| 39 | +oper_array(sum, a, 0) => [18, 87, -3, -81, -16, 24] |
| 40 | +oper_array(min, a, a[0]) => [18, 18, -90, -90, -90, -90] |
| 41 | +oper_array(max, a, a[0]) => [18, 69, 69, 69, 69, 69] |
| 42 | +``` |
| 43 | +#### Notes: |
| 44 | +- The form of the parameter `fct` in oper_array (or operArray or oper-array) |
| 45 | +changes according to the language. You can see each form according to the language in "Your test cases". |
| 46 | +
|
| 47 | +- AFAIK there are no corner cases, everything is as nice as possible. |
| 48 | +
|
| 49 | +- lcm and gcd see: |
| 50 | +<https://en.wikipedia.org/wiki/Least_common_multiple> |
| 51 | +<https://en.wikipedia.org/wiki/Greatest_common_divisor> |
| 52 | +
|
| 53 | +- you could google "reduce function (your language)" to have a general view about the reduce functions. |
| 54 | +
|
| 55 | +- In Shell bash, arrays are replaced by strings. |
| 56 | +- In OCaml arrays are replaced by lists. |
| 57 | +
|
| 58 | +""" |
| 59 | + |
| 60 | +from itertools import accumulate |
| 61 | +from math import lcm |
| 62 | +from math import gcd |
| 63 | + |
| 64 | +def gcdi(a, b): return gcd(a, b) |
| 65 | +def lcmu(a, b): return lcm(a, b) |
| 66 | +def som(a, b): return a + b |
| 67 | +def maxi(a, b): return max(a, b) |
| 68 | +def mini(a, b): return min(a, b) |
| 69 | + |
| 70 | +def oper_array(fct, arr, init): |
| 71 | + return list(accumulate(arr, fct, initial=init))[1:] |
0 commit comments